Homesand
Homesand

Reputation: 423

How to find the position of number in a string list?

 a = ['+321','+09e8','\sdf5234','6']

I want to convert it into a list of all numbers. In other words, remove all non-digit characters from all the strings from the list. The result should be a list of integers not strings.

[321,98, 5234, 6]

Any help is much appreciated! Thanks

Upvotes: 0

Views: 249

Answers (3)

jpp
jpp

Reputation: 164833

Without regex, you can use str.isdigit with a list comprehension:

a = ['+321','+09e8','\sdf5234','6']

res = [int(''.join([i for i in x if i.isdigit()])) for x in a]

[321, 98, 5234, 6]

Upvotes: 0

Matthew Smith
Matthew Smith

Reputation: 508

Something simple and easy to understand like this will do the trick...

a = ['+321','+09e8','\sdf5234','6']
b = []
c = ''

for item in a:
    for char in item:
        if char.isdigit():
             c += char
    b.append(int(c))
    c = ''

print(b)

It loops through every item in the list a and loops through each character of a. It checks if the character is a number and if so, adds it to the string to add to the output (b)

Hope that helps!

Upvotes: 1

Praveen
Praveen

Reputation: 9355

You can use re.sub

In [1]: import re

In [2]: a = ['+321','+09e8','\sdf5234','6']

In [3]: [int(re.sub('[^0-9]','',x)) for x in a]
Out[3]: [321, 98, 5234, 6]

Here re.sub('[^0-9]','',x) will replace all the characters other than numbers(0-9) from the string.

Upvotes: 2

Related Questions