Dturner
Dturner

Reputation: 3

Turn text into a string of letters in python?

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

Answers (5)

Nick Edwards
Nick Edwards

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

cdarke
cdarke

Reputation: 44344

The re.findall() method will create a list of matching strings, and a simple list comprehension converts them to ints.

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

zondo
zondo

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

Gareth McCaughan
Gareth McCaughan

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

aghast
aghast

Reputation: 15300

This sounds like classwork, so try this:

  1. Use str.split to divide the sentence into words.
  2. Use str.isdigit to determine which words are all digits.
  3. Use int() to convert the digit-only words into integers.
  4. Return the list.

Upvotes: 2

Related Questions