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


- 我如何卸载 PyTorch? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01