Read numbers in a string with any number of digits in python

92 views Asked by At

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.

5

There are 5 answers

2
Ruben Bermudez On BEST ANSWER

You can use split() and then print the second element of the generated list:

name='report 112 hits'
namelist = name.split()
print(namelist[0])
# report
print(namelist[1])
# 112
print(namelist[2])
# hits
0
Russia Must Remove Putin On
import re

name='report 11155342 hits'

print(re.findall(r'\d+', name)[0])

prints:

11155342
1
thefourtheye On
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.

0
jonrsharpe On

Assuming there will always be spaces:

_, count, hits = name.split(" ")
print(count)
print(hits)
3
jgritty On

If you are guaranteed that the string is always 'report ### hits' where ### is some number of digits, you could do:

name = 'report 11155342 hits'
print name.split()[1]
print name.split()[2]