Python - 检查字符串中的最后一个字符是否为数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14471177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - Check if the last characters in a string are numbers
提问by user2002290
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:
我知道对于这个特定的字符串,您可以使用正则表达式来确定它是否以数字结尾,然后使用 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[:] 选择数字。我希望我能清楚地解释我需要什么,以便你们提供帮助。谢谢!
采纳答案by Peter Graham
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()
\dmatches 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+表示匹配一个或多个数字(贪婪:匹配尽可能多的连续数字)。并且$表示匹配字符串的结尾。
回答by RocketDonkey
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 :)
我完全完全支持正则表达式解决方案,但这里有一种(不漂亮的)方法可以获得数字。同样,正则表达式在这里要好得多:)
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'
回答by Thai Tran
another solution:
另一种解决方案:
a = "abc1323"
b = ""
for c in a[::-1]:
try:
b += str(int(c))
except:
break
print b[::-1]
回答by kojiro
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:
由于空字符串是falsy,您可以重载含义:
def getNumericTail(str):
re.split('[^\d]', str)[-1]
def endsWithNumber(str):
bool(getNumericTail(str))
回答by Hans Bouwmeester
Another solution: see how many 0-9 digits you can strip of the end of stringand use that length as an index into stringto split of the number.
(Returns ''in case stringdoes not end in a number).
另一种解决方案:查看您可以去除字符串末尾的 0-9 位数,并将该长度用作字符串的索引以拆分数字。(''如果字符串不以数字结尾则返回)。
In [1]: s = '12hello123558'
In [2]: s[len(s.rstrip('0123456789')):]
Out[2]: '123558'

