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]
.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With