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

2022-01-17 00:00:00 python string regex numbers

问题描述

基本上我想知道我会怎么做.

Basically I want to know how I would do this.

这是一个示例字符串:

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.

我知道对于这个特定的字符串,您可以使用正则表达式来确定它是否以数字结尾,然后使用 string[:] 选择123".但是如果我正在循环一个带有这样字符串的文件:

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:

hello123
hello12324
hello12435436346

...由于数字长度的差异,我将无法使用 string[:] 选择数字.我希望我能清楚地解释我需要什么来帮助你们.谢谢!

...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!


解决方案

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 匹配一个数字,d+ 表示匹配一个或多个数字(贪心:匹配尽可能多的连续数字).而 $ 表示匹配字符串的结尾.


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.

相关文章