可以使用正则表达式对字符串进行分割,以最后一个数字为分割点:

import re

s = "hello123world456"
match = re.search(r'\d+', s[::-1])  # 从字符串末尾开始查找数字
if match:
    index = len(s) - match.end()  # 获取数字在字符串中的位置
    text, number = s[:index], s[index:]
    print(text)  # 输出:hello123world
    print(number)  # 输出:456
else:
    print("No number found.")

这里使用了正则表达式 \d+ 匹配字符串中的数字, [::-1] 表示将字符串倒序,从末尾开始查找数字。如果匹配到了数字,则可以根据数字在字符串中的位置将字符串分割成两部分。

python 一个字符串中包含文字和数字现在先以最后一个数字进行分割

原文地址: https://www.cveoy.top/t/topic/fsfb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录