Python - Check if the last characters in a string are numbers(Python - 检查字符串中的最后一个字符是否是数字)
问题描述
基本上我想知道我会怎么做.
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.
这篇关于Python - 检查字符串中的最后一个字符是否是数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python - 检查字符串中的最后一个字符是否是数字


基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01