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 - 检查字符串中的最后一个字符是否是数字


基础教程推荐
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01