4

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?

Alok
  • 87
  • 1
  • 10

6 Answers6

3

You can do it with

val.strip('[]').split()
user2397282
  • 3,798
  • 15
  • 48
  • 94
1

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']
Austin
  • 25,759
  • 4
  • 25
  • 48
1
>>> val
'[12 13 14 16 17 18]'
>>> val.strip("[]").split(" ")
['12', '13', '14', '16', '17', '18']
gspoosi
  • 355
  • 1
  • 9
0

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']
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0

if you realy need the paranthesis

val = '[12 13 14 16 17 18]'
val = val.replace('[','')
val = val.replace(']','')
val = val.split(' ')
user3732793
  • 1,699
  • 4
  • 24
  • 53
0

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'>
jpp
  • 159,742
  • 34
  • 281
  • 339