Skip to content

Instantly share code, notes, and snippets.

@bbookman
Created December 26, 2018 22:18
Show Gist options
  • Save bbookman/ad4a1d6e9e9c752bf5ec899de0ca82dc to your computer and use it in GitHub Desktop.
Save bbookman/ad4a1d6e9e9c752bf5ec899de0ca82dc to your computer and use it in GitHub Desktop.
Python List Comprehension: Find numbers in sentence
'''
Get only the numbers in a sentence like 'In 1984 there were 13 instances of a protest with over 1000 people attending'. Result is a list of numbers like [3,4,5]
'''
sentence = 'In 1984 there were 13 instances of a protest with over 1000 people attending'
words = sentence.split()
result = [number for number in words if not number.isalpha() ]
print(result)
@Folskyy
Copy link

Folskyy commented Jun 15, 2024

"""
Get only the numbers in a sentence like
'In 1984 there were 13 instances of a protest with over 1000 people attending'
"""

string = 'In 1984 there were 13 instances of a protest with over 1000 people attending'
only_num = [int(i) for i in string if i in '1234567890']

@ashar73
Copy link

ashar73 commented Jul 4, 2024

str1="In 1984 there were 13 instances of a protest with over 1000 people attending"
res=[x for x in str1 if ord(x)>=48 and ord(x)<=57]
print(res)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment