Python - 检查字符串中的最后一个字符是否为数字 [英] Python - Check if the last characters in a string are numbers

查看:85
本文介绍了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 - 检查字符串中的最后一个字符是否为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆