creating list with only numeric values from list of strings

Viewed 77

Basically, I want to create a list of numeric values from a list of strings. I wrote a simple while loop to check each character in each string in the list, but it's not returning as expected. Is there a better way of doing this or am I messing something up? Here is my code:

textList = ["3", "2 string", "3FOO"]
newList = []
i= 0
foo = 0
while i < len(textList):
    tmplist=[]
    while foo < len(textList[i]):
        bar = textList[i]
        if bar[foo].isnumeric():
            tmplist.append(str(bar[foo]))
        foo += 1
    tmpstring = str(''.join(tmplist))
    newList.append(tmpstring)
    i += 1
print(newList)

The expected output is

["3", "2", "3"]

However, I get:

["3", "", ""]

Can anyone explain why?
4 Answers

Use Regex. re.match

Ex:

import re

textList = ["3", "2 string", "3FOO"]
newList = []
ptrn = re.compile(r"(\d+)")
for i in textList:
    m = ptrn.match(i)
    if m:
        newList.append(m.group(0))
print(newList)  # -->['3', '2', '3']

you forgot to reset 'foo' to 0 after each iteration
try this:

textList = ["3", "2 string", "3FOO"]
newList = []
i= 0
while i < len(textList):
    tmplist=[]
    foo = 0
    while foo < len(textList[i]):
        bar = textList[i]
        if bar[foo].isnumeric():
            tmplist.append(str(bar[foo]))
        foo += 1
    tmpstring = str(''.join(tmplist))
    newList.append(tmpstring)
    i += 1
print(newList)

You can simplify the code greatly by using for loops and list comprehensions instead of while.

textList = ["3", "2 string", "3FOO"]
newList = []
for s in textList:
    numlist = [c for c in s if c.isnumeric()]
    newList.append("".join(numlist))

This is because you set the variable foo=0 in line 4, the foo value keeps increasing as it read the element in textList.

I add

print(str(foo) +" "+ str(bar[foo]))

in line number 9 to check what happened.

textList = ["3", "2 string", "3FOO"]
newList = []
i= 0
foo = 0
while i < len(textList):
    tmplist=[]
    while foo < len(textList[i]):
        bar = textList[i]
        print(str(foo) +" "+ str(bar[foo]))
        if bar[foo].isnumeric():
            tmplist.append(str(bar[foo]))
        foo += 1
    tmpstring = str(''.join(tmplist))
    newList.append(tmpstring)
    i += 1
print(newList)

The result would be like this.

0 3
1  
2 s
3 t
4 r
5 i
6 n
7 g
['3', '', '']

This means it does not read the first character in the second and third elements.

So, you need to reset the foo value, just remove the foo from line 4, and add it after line 6.

textList = ["3", "2 string", "3FOO"]
newList = []
i= 0
# foo = 0
while i < len(textList):
    tmplist=[]
    foo = 0
    while foo < len(textList[i]):
        bar = textList[i]
        if bar[foo].isnumeric():
            tmplist.append(str(bar[foo]))
        foo += 1
    tmpstring = str(''.join(tmplist))
    newList.append(tmpstring)
    i += 1
print(newList)
Related