Alok
Alok

Reputation: 87

Converting a list into comma separated and add quotes in python

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

Answers (6)

gspoosi
gspoosi

Reputation: 365

>>> val
'[12 13 14 16 17 18]'
>>> val.strip("[]").split(" ")
['12', '13', '14', '16', '17', '18']

Upvotes: 1

jpp
jpp

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

Austin
Austin

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

user3732793
user3732793

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

Vasilis G.
Vasilis G.

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

user2397282
user2397282

Reputation: 3818

You can do it with

val.strip('[]').split()

Upvotes: 3

Related Questions