Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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].

like image 726
lamps8 Avatar asked Jan 01 '23 20:01

lamps8


2 Answers

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.

like image 67
taurus05 Avatar answered Jan 05 '23 16:01

taurus05


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]
like image 38
AnkushRasgon Avatar answered Jan 05 '23 15:01

AnkushRasgon