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?
你可以做到
val.strip('[]').split()
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']
>>> val
'[12 13 14 16 17 18]'
>>> val.strip("[]").split(" ")
['12', '13', '14', '16', '17', '18']
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']
if you realy need the paranthesis
val = '[12 13 14 16 17 18]'
val = val.replace('[','')
val = val.replace(']','')
val = val.split(' ')
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'>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.