Reputation: 87
I have :
val = '[12 13 14 16 17 18]'
I want to have:
['12','13','14','16','17','18']
I have done
x = val.split(' ')
y = (" , ").join(x)
The result is
'[12 , 13 , 14 , 16 , 17 , 18 ]'
But not the exact one also the quotes
What's the best way to do this in Python?
Upvotes: 4
Views: 3833
Reputation: 365
>>> val
'[12 13 14 16 17 18]'
>>> val.strip("[]").split(" ")
['12', '13', '14', '16', '17', '18']
Upvotes: 1
Reputation: 164843
You can use ast.literal_eval
after replacing whitespace with comma:
from ast import literal_eval
val = '[12 13 14 16 17 18]'
res = list(map(str, literal_eval(val.replace(' ', ','))))
print(res, type(res))
['12', '13', '14', '16', '17', '18'] <class 'list'>
Upvotes: 0
Reputation: 26057
Only if you can handle a regex
:
import re
val = '[12 13 14 16 17 18]'
print(re.findall(r'\d+', val))
# ['12', '13', '14', '16', '17', '18']
Upvotes: 1
Reputation: 1979
if you realy need the paranthesis
val = '[12 13 14 16 17 18]'
val = val.replace('[','')
val = val.replace(']','')
val = val.split(' ')
Upvotes: 0
Reputation: 7859
You can use this:
val = '[12 13 14 16 17 18]'
val = val[1:-1].split()
print(val)
Output:
['12', '13', '14', '16', '17', '18']
Upvotes: 0