Reputation: 3
So I am trying to make a piece if code that can take a string, ignore all plain text in it, and return a list of numbers but I am running into trouble.
basically, I want to turn "I want to eat 2 slices of pizza for dinner, and then 1 scoop of ice cream for desert" into [2,1] (just an example)
dummy = dummy.split(" ")
j = 0
for i in dummy:
dummy[j]=i.rstrip("\D")
j+=1
print(dummy[j-1])
is what i have tried but it didn't remove anything. i tried the rstrip("\D") because i thought that was supposed to remove text but does not seem to work for a list.
any ideas where i went wrong or ways to fix this?
Upvotes: 0
Views: 820
Reputation: 610
One way of doing this would be something like
dummy = [int(c) for c in dummy.split(" ") if c.isdigit() ]
This would only pick up numbers separated by spaces on either side though (e..g "2cm" would not be picked up).
Upvotes: 0
Reputation: 44344
The re.findall()
method will create a list of matching strings, and a simple list comprehension converts them to int
s.
import re
dummy = "I want to eat 2 slices of pizza for dinner, and then 1 scoop of ice cream for desert"
result = [int(d) for d in re.findall(r'\d+', dummy)]
print(result)
gives:
[2, 1]
Upvotes: 0
Reputation: 20336
You can do this with a regular expression:
import re
string = "I want to eat 12 slices of pizza for dinner, and then 1 scoop of ice cream for desert"
numbers = list(map(int, re.findall(r"\d+", string)))
print(numbers)
#[12, 1]
The str.rstrip()
method, however, does not use regular expressions, so that's why yours didn't work.
Upvotes: 0
Reputation: 19971
You could use re.split
for this (slightly along the lines of the code you've posted, where as TigerhawkT3 observes you appear to be mixing up regular expressions with strings) but even better for your purpose is re.findall
. That plus calling int
to turn numeric strings into actual integers will do the job.
Upvotes: 0
Reputation: 15300
This sounds like classwork, so try this:
Upvotes: 2