如何在Python3中选择字符串中最后一个字符后的所有数字?

2024-09-30 19:22:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从这样的结构中解析出最后的数字:"q1option4"->4。另一个例子:"q3option54->54。我知道在Python3中可能有一种优雅的方法可以做到这一点,所以我正在寻求您的帮助。谢谢


Tags: 方法数字结构python3例子q1option4gt4gt54
3条回答

您可以为此使用正则表达式:

import re

re.search(r"(\d+)$", "q1option54").group()

54

import re

regex = re.compile(r'^(?:[a-zA-z]*\d*[a-zA-z]+)*(\d+)$')
examples = [
    "q1option4",
    "q3option54",
    "q3op23ti56on18",
    "q28",
    "11",
]

for e in examples:
    print(e, '-->', regex.match(e).groups()[0])

Outuput

q1option4 --> 4
q3option54 --> 54
q3op23ti56on18 --> 18
q28 --> 28
11 --> 11

如果您知道所有的数字都在字符串的末尾,在一个不间断的序列中,那么从字符串的末尾开始搜索第一个字母

seq = "q3option54"
seq_rev = seq[::-1] # reverse the sequence
rev_ind = 0

# find the last sequence of numbers
for ind, char in enumerate(seq_rev):
    if not char.isdigit():
        rev_ind = ind
        break

# slice off the digit part, and reverse it
digits = seq_rev[:rev_ind][::-1]
print(f'digits: {digits}')

输出:

digits: 54

相关问题 更多 >