2024-05-29 02:37:26 发布
网友
我有一个包含数字的字符串,以x开头,例如,"x270"或"x9"。它总是以x开头。我需要知道电话号码
"x270"
"x9"
我正在这样做:
blatz = "x22" a1 = int(re.search("x(\d+)", blatz).group(1))
这看起来不太像Python。我欢迎更优雅的解决方案
请看看这个
import re blatz = "x22" print(re.search("\d", blatz).group())
使用re库似乎是一种过度使用。您不必搜索模式,因为您的意思是每个字符串都以x开头
re
x
因此,您只需执行slicing:
blatz = "x22" a1 = int(blatz[1:])
如果需要进一步检查,可以查看str.startswith()、str.endswith和/或str.isdigit()
虽然切片看起来很像Python,但也有可能使用other string methods实现相同的目标:
blatz = "x22" a2 = int(blatz.lstrip("x")) # strip "x" from the left a3 = int(blatz.partition("x")[-1]) # get everything after "x" a4 = int(blatz.replace("x", "")) # replace every "x" with empty string ...
但是切片速度更快,对于Python程序员来说也没什么不寻常的
请看看这个
使用
re
库似乎是一种过度使用。您不必搜索模式,因为您的意思是每个字符串都以x
开头因此,您只需执行slicing:
如果需要进一步检查,可以查看str.startswith()、str.endswith和/或str.isdigit()
虽然切片看起来很像Python,但也有可能使用other string methods实现相同的目标:
但是切片速度更快,对于Python程序员来说也没什么不寻常的
相关问题 更多 >
编程相关推荐