[英]Read numbers in a string with any number of digits in python
I am having trouble in parsing my string. 我在解析字符串时遇到麻烦。 Here are my codes: 这是我的代码:
name='report 11 hits'
print(name[7:9])
print(name[11:])
output: 输出:
11
hits
But, if I need to type the string as 但是,如果我需要将字符串键入为
name='report 112 hits'
print(name[7:9])
print(name[10:])
output: 输出:
11
hits
That means, whenever I am typing a number more than three digits, the program is not reading it well. 这意味着,每当我输入超过三位数的数字时,程序都无法很好地读取它。 I was wondering if someone could write me how to modify my code in such a way that no matter what digit I write, the program will read it correctly. 我想知道是否有人可以写我如何修改我的代码,使得无论我写什么数字,程序都可以正确读取它。 Thanks. 谢谢。
You can use split()
and then print the second element of the generated list: 您可以使用split()
,然后打印生成的列表的第二个元素:
name='report 112 hits'
namelist = name.split()
print(namelist[0])
# report
print(namelist[1])
# 112
print(namelist[2])
# hits
name='report 112 hits'
import re
print re.search(r'\d+', name).group()
# 112
But if you know for sure that the number will be the second element in the string, separated by a space, then you can do 但是,如果您确定数字将是字符串中的第二个元素,并用空格分隔,则可以
print name.split(None, 2)[1]
# 112
This split will be efficient as we limit the maximum splitting by 2. 由于我们将最大分割数限制为2,因此这种分割将非常有效。
Assuming there will always be spaces: 假设总会有空格:
_, count, hits = name.split(" ")
print(count)
print(hits)
If you are guaranteed that the string is always 'report ### hits' where ### is some number of digits, you could do: 如果您确保该字符串始终是“ report ### hits”(其中###是一些数字),则可以执行以下操作:
name = 'report 11155342 hits'
print name.split()[1]
print name.split()[2]
import re
name='report 11155342 hits'
print(re.findall(r'\d+', name)[0])
prints: 印刷品:
11155342
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.