Python -检查字符串中的最后一个字符是否是数字。

时间:2022-12-29 20:21:53

Basically I want to know how I would do this.

基本上我想知道我该怎么做。

Here's an example string:

这里有一个例子字符串:

string = "hello123"

I would like to know how I would check if the string ends in a number, then print the number the string ends in.

我想知道如何检查字符串以数字结尾,然后打印字符串结束的数字。

I know for this certain string you could use regex to determine if it ends with a number then use string[:] to select "123". BUT if I am looping through a file with strings like this:

我知道对于这个特定的字符串,您可以使用regex来确定它是否以数字结尾,然后使用string[:]来选择“123”。但是如果我用这样的字符串在文件中循环

hello123
hello12324
hello12435436346

...Then I will be unable to select the number using string[:] due to differentiation in the number lengths. I hope I explained what I need clearly enough for you guys to help. Thanks!

…然后,由于数字长度的差异,我将无法使用string[:]来选择数字。我希望我能清楚地向你们解释我需要的东西。谢谢!

5 个解决方案

#1


42  

import re
m = re.search(r'\d+$', string)
# if the string ends in digits m will be a Match object, or None otherwise.
if m is not None:
    print m.group()

\d matches a numerical digit, \d+ means match one-or-more digits (greedy: match as many consecutive as possible). And $ means match the end of the string.

\d匹配一个数字,\d+表示匹配一个或多个数字(贪心:匹配尽可能多的连续数字)。$表示匹配字符串的末尾。

#2


15  

This doesn't account for anything in the middle of the string, but it basically says that if the last number is a digit, it ends with a number.

这并不能解释字符串中间的任何东西,但它基本上是说如果最后一个数字是一个数字,它就以一个数字结束。

In [4]: s = "hello123"

In [5]: s[-1].isdigit()
Out[5]: True

With a few strings:

有一些字符串:

In [7]: for s in ['hello12324', 'hello', 'hello1345252525', 'goodbye']:
   ...:     print s, s[-1].isdigit()
   ...:     
hello12324 True
hello False
hello1345252525 True
goodbye False

I fully and completely support the regex solution(s), but here is one (not pretty) way you could get the number. Again, regex is much better here :)

我完全支持regex解决方案,但是这里有一种(不是很好的)方法可以得到这个数字。再一次,regex在这里要好得多:)

In [43]: from itertools import takewhile

In [44]: s = '12hello123558'

In [45]: r = s[-1::-1]

In [46]: d = [c.isdigit() for c in r]

In [47]: ''.join((i[0] for i in takewhile(lambda (x, y): y, zip(r, d))))[-1::-1]
Out[47]: '123558'

#3


1  

This one will simply return an empty string if the string ends with something that is not a number.

如果字符串以非数字的形式结束,这个将返回空字符串。

import re
re.split('[^\d]', str)[-1]

Since an empty string is falsy, you can overload the meaning:

由于空字符串是假的,您可以重载它的含义:

def getNumericTail(str):
    re.split('[^\d]', str)[-1]

def endsWithNumber(str):
    bool(getNumericTail(str))

#4


0  

another solution:

另一个解决方案:

a = "abc1323"
b = ""
for c in a[::-1]:
    try:
        b += str(int(c))
    except: 
        break

print b[::-1]

#5


0  

Another solution: see how many 0-9 digits you can strip of the end of string and use that length as an index into string to split of the number. (Returns '' in case string does not end in a number).

另一种解决方案是:看看可以去掉多少个0-9位数字,然后用这个长度作为索引将数字分割成字符串。(返回“以防字符串以数字结尾)。

In [1]: s = '12hello123558'

In [2]: s[len(s.rstrip('0123456789')):]
Out[2]: '123558'

#1


42  

import re
m = re.search(r'\d+$', string)
# if the string ends in digits m will be a Match object, or None otherwise.
if m is not None:
    print m.group()

\d matches a numerical digit, \d+ means match one-or-more digits (greedy: match as many consecutive as possible). And $ means match the end of the string.

\d匹配一个数字,\d+表示匹配一个或多个数字(贪心:匹配尽可能多的连续数字)。$表示匹配字符串的末尾。

#2


15  

This doesn't account for anything in the middle of the string, but it basically says that if the last number is a digit, it ends with a number.

这并不能解释字符串中间的任何东西,但它基本上是说如果最后一个数字是一个数字,它就以一个数字结束。

In [4]: s = "hello123"

In [5]: s[-1].isdigit()
Out[5]: True

With a few strings:

有一些字符串:

In [7]: for s in ['hello12324', 'hello', 'hello1345252525', 'goodbye']:
   ...:     print s, s[-1].isdigit()
   ...:     
hello12324 True
hello False
hello1345252525 True
goodbye False

I fully and completely support the regex solution(s), but here is one (not pretty) way you could get the number. Again, regex is much better here :)

我完全支持regex解决方案,但是这里有一种(不是很好的)方法可以得到这个数字。再一次,regex在这里要好得多:)

In [43]: from itertools import takewhile

In [44]: s = '12hello123558'

In [45]: r = s[-1::-1]

In [46]: d = [c.isdigit() for c in r]

In [47]: ''.join((i[0] for i in takewhile(lambda (x, y): y, zip(r, d))))[-1::-1]
Out[47]: '123558'

#3


1  

This one will simply return an empty string if the string ends with something that is not a number.

如果字符串以非数字的形式结束,这个将返回空字符串。

import re
re.split('[^\d]', str)[-1]

Since an empty string is falsy, you can overload the meaning:

由于空字符串是假的,您可以重载它的含义:

def getNumericTail(str):
    re.split('[^\d]', str)[-1]

def endsWithNumber(str):
    bool(getNumericTail(str))

#4


0  

another solution:

另一个解决方案:

a = "abc1323"
b = ""
for c in a[::-1]:
    try:
        b += str(int(c))
    except: 
        break

print b[::-1]

#5


0  

Another solution: see how many 0-9 digits you can strip of the end of string and use that length as an index into string to split of the number. (Returns '' in case string does not end in a number).

另一种解决方案是:看看可以去掉多少个0-9位数字,然后用这个长度作为索引将数字分割成字符串。(返回“以防字符串以数字结尾)。

In [1]: s = '12hello123558'

In [2]: s[len(s.rstrip('0123456789')):]
Out[2]: '123558'