Skip to content

Instantly share code, notes, and snippets.

@bbookman
Created December 26, 2018 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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)
@Kronekuto507
Copy link

string = "In 1984 there were 13 instances of a protest with over 13 people attending".split()
print(string)

list_a = [a for a in string if a[0] in ("1","2","3","4","5","6","7","8","9","0") ]
print(list_a)

@Amine-Fadssi
Copy link

Amine-Fadssi commented Jan 11, 2024

# Get only the numbers in a sentence
sentence = 'In 1984 there were 13 instances of a protest with over 1000 people attending'
my_list = [item for item in sentence if item.isnumeric()]
print(my_list)

@AkhonaDlamini
Copy link

sentence = 'In 1984 there were 13 instances of a protest with over 1000 people attending'
#If we were about to return one integer at a time like [1, 9, 8, 4, 1, 3, 1, 0, 0, 0] rather than 1984, 13, 1000 we would do it like this:

nums = [number for number in sentence if number.isdigit() == True]
print(nums)

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