Reputation: 105
How do I print the numbers in a string in Python? In the example below, I am able to print the 6. How do I print the 6 and 5 together? Giving me 65.
man = 'The man is 65 or older'
print(man[11])
Upvotes: 0
Views: 1989
Reputation: 402483
I can think of two ways that don't involve hardcoding your index.
str.split
with str.isdigit
numbers = [x for x in string.split() if x.isdigit()]
print(numbers)
['65']
re.findall
import re
numbers = re.findall(r'\b\d+\b', string)
print(numbers)
['65']
Regex Details
\b # word boundary
\d+ # match 1 or more digits
\b # word boundary
Note that the \b
word boundary should be used if you want to return only those numbers that are not part of a bigger word (for example, 3D
will not be counted here).
Upvotes: 6
Reputation: 158
How about this short code?
man = 'The man is 65 or older'
numbers = list(filter(str.isdigit, man.split(' ')))
print(numbers[0])
Upvotes: 2