python - 从字符串中提取数字的最 Pythonic 方法

标签 python regex python-3.x

我有一个包含数字的字符串,以x开头,例如"x270""x9" 。它总是以x开头。我需要获取号码。

我正在这样做:

blatz = "x22"
a1 = int(re.search("x(\d+)", blatz).group(1))

这看起来不太 Pythonic。我欢迎更多优雅的解决方案。

最佳答案

使用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 程序员来说没什么不寻常的。

关于python - 从字符串中提取数字的最 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60528050/

相关文章:

python - 无法完全删除 PyQt QGraphicsView 的边框

python - Pandas Melt with Multi Index Data Set and Resetting Index - 为什么这有效?

java - 正则表达式查找用空格分隔的单词

python - 正则表达式 Python 排除一些结果

Python 无法在 Ubuntu 14.04 上运行(可信) - 无法导入标准库

python - 在不使用 os.chdir() 的情况下在 python 中创建相对符号链接(symbolic link)

javascript - .test() 的正则表达式漏报

python - 检测生成器函数是否为空,否则迭代它

python-3.x - [ :] in overwriting a list in a for loop? 的作用是什么

python - 按字典中键的值合并两个字典列表