lamps8
lamps8

Reputation: 53

How to convert elements of string to list using a regex?

In a code I'm trying to write, I want to convert a string which contains numbers to a list where each element is a number of that string.

I tried to use sub, a re function, but I don't have the result I want in a particular case.

x = "8 1 2 9 12"
liste= []
final = []

for s in x:
    liste.append(re.sub('\s+',"", s))
for element in liste:
    if element =="":
        liste.remove("")

for b in liste:
    if b != 'X':
        final += [int(b)]
    else:
        final+=["X"]

I expect the output of [8,1,2,9,12], but the actual output is [8,1,2,9,1,2].

Upvotes: 4

Views: 1001

Answers (3)

taurus05
taurus05

Reputation: 2546

You can do it very easily using split and conversion. The necessary condition to use this approach is that the string should only contain digits and whitespaces and no other character should present.

>>> li = "8 1 2 9 12"
>>> result = [int(i) for i in li.split(' ')]
>>> print(result)
[8, 1, 2, 9, 12]

Now, moving on to your implementation, inside the first for loop, for s in x:, it iterates over the string. Hence, s takes following values :

>>> for s in x:
...     print(s)
...
8

1

2

9

1
2

This results in creation of 6 integer values, which are actually 5, when the string is manually inspected. This is the main reason, why you are not getting the expected outcome.
If the string would have been something like x = "12345", it would have returned, [1,2,3,4,5], which is wrong.

Upvotes: 5

Lê Tư Thành
Lê Tư Thành

Reputation: 1083

The previous answer is the best practice for you, but I also suggest another way for your consider to use: Regular Expression

>>>import re
>>>x = "8 1 2 9 12"
>>>list(map(int, re.findall(r'\d+', x)))
[8, 1, 2, 9, 12]

Upvotes: 1

AnkushRasgon
AnkushRasgon

Reputation: 820

you only need to use split method if there are only whitespaces and digits

x = "8 1 2 9 12"
print([int(i) for i in x.split()])

output:
[8, 1, 2, 9, 12]

Upvotes: 3

Related Questions