gpt4 book ai didi

python - 如何从以减号分隔的字符串中提取数字

转载 作者:行者123 更新时间:2023-11-30 23:20:10 25 4
gpt4 key购买 nike

我需要能够从字符串中提取两个数字。我知道这两个数字(如果以字符串形式出现)用“-”字符彼此分隔。

a='some text'
b='some 0-376 text'
c='some text.0-376.some text again'
d='some text.0-376####.jpg'

显然我需要以简单但可靠的方式提取零0376。因此,无论数字位于字符串中的哪个位置,代码都可以工作:在开头、中间或结尾。无论数字周围有什么字符,它都应该提供恒定的结果:字母、逗号、句点、美元或英镑符号等。

最佳答案

这听起来像是正则表达式的工作:

import re

a='some text'
b='some 0-376 text'
c='some text.0-376.some text again'
d='some text.0-376####.jpg'


for text in a, b, c, d:
match = re.search(r'(\d+)-(\d+)', text)
if match:
left, right = map(int, match.groups())
print left, right

关于python - 如何从以减号分隔的字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25675921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com