Python找到一个数字,然后从字符串中复制它

2024-09-28 03:16:45 发布

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

所以我有一个字符串,比如"abdc54sgh",我只需要从字符串中复制54。问题是数字之前的数字可能会有所不同。e、 j.字符串可以是"hjsd23jsy""abvt12hbsy"或任何其他字符串。所以我只需要复制数字,第一个是23,第二个是12,然后把它赋给一个变量。你知道吗


Tags: 字符串数字abdc54sghabvt12hbsyhjsd23jsy
2条回答

请尝试以下操作:

def takeInt(st):
    return int("".join([ch for ch in st if not ch.isalpha()]))

>>> takeInt("hjsd23jsy")
23
>>> takeInt("abvt12hbsy")
12
>>> 

使用正则表达式:

import re
s = "abdc54sgh"
pattern = re.compile("\d+")
pattern.findall(s)

或列表理解和isdigit()

s = "abdc54sgh"
int("".join([x for x in s if x.isdigit()]))

相关问题 更多 >

    热门问题