2024-09-28 03:16:45 发布
网友
所以我有一个字符串,比如"abdc54sgh",我只需要从字符串中复制54。问题是数字之前的数字可能会有所不同。e、 j.字符串可以是"hjsd23jsy"或"abvt12hbsy"或任何其他字符串。所以我只需要复制数字,第一个是23,第二个是12,然后把它赋给一个变量。你知道吗
"abdc54sgh"
"hjsd23jsy"
"abvt12hbsy"
请尝试以下操作:
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():
isdigit()
s = "abdc54sgh" int("".join([x for x in s if x.isdigit()]))
请尝试以下操作:
使用正则表达式:
或列表理解和
isdigit()
:相关问题 更多 >
编程相关推荐