深度阅读

How to Find Last Number in String in Python

作者
作者
2023年08月22日
更新时间
8.28 分钟
阅读时间
0
阅读量

To find the last number in a string in Python, you can use regular expressions. Here’s an example implementation:

import re

my_string = "Hello world 47"
match = re.search('\d+$', my_string)

if match:
    last_number = match.group()
    print(last_number)
else:
    print("No number found")

In this example, the \d pattern matches any digit, and the + qualifier matches one or more consecutive digits. The $ matches the end of the string. The code then prints the last number found in the string as a string (in this case, “47”).

Note that this implementation assumes that the number you’re looking for only contains digits. If there are other characters in the number, you’ll need to modify the regular expression accordingly. Also, if there is no number in the string, the code prints “No number found”.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。