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?
asked Jul 30, 2018 at 14:40
5
You can do it with
val.strip['[]'].split[]
answered Jul 30, 2018 at 14:42
user2397282user2397282
3,77815 gold badges44 silver badges93 bronze badges
0
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']
answered Jul 30, 2018 at 14:49
AustinAustin
25.4k4 gold badges22 silver badges47 bronze badges
>>> val
'[12 13 14 16 17 18]'
>>> val.strip["[]"].split[" "]
['12', '13', '14', '16', '17', '18']
answered Jul 30, 2018 at 14:51
gspoosigspoosi
3551 silver badge9 bronze badges
1
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']
answered Jul 30, 2018 at 14:45
Vasilis G.Vasilis G.
7,3334 gold badges19 silver badges28 bronze badges
if you realy need the paranthesis
val = '[12 13 14 16 17 18]'
val = val.replace['[','']
val = val.replace[']','']
val = val.split[' ']
answered Jul 30, 2018 at 14:47
user3732793user3732793
1,6083 gold badges21 silver badges40 bronze badges
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']
answered Jul 30, 2018 at 14:48
jppjpp
152k31 gold badges256 silver badges318 bronze badges
1
In Python Scripting, I have a string abc=[9874,209384,20938]
I want the output as abc=["9874","209384","20938"]
My efforts got me "9874" "209384" "20938"
but I want like this ["9874","209384","20938"]
asked May 7, 2019 at 22:37
bruce_karlobruce_karlo
131 gold badge1 silver badge2 bronze badges
1
- strip the
[]
:abc[1:-1]
- split on
,
:.split[',']
- bracket each element with
""
:'"'+x+'"'
- join with
,
:','.join
- add the
[]
:'['+...+']'
TL;DR:
'['+','.join[['"'+x+'"' for x in abc[1:-1].split[',']]]+']'
answered May 8, 2019 at 7:39
xenoidxenoid
9,4183 gold badges19 silver badges31 bronze badges
It's hard to tell what you want as your question isn't very precise, something like this?
abc = [9874,209384,20938]
abc_str = []
for n in abc:
abc_str.append[str[n]]
print[abc_str]
answered May 8, 2019 at 2:03
Maybe this
for i in range[len[abc]]: abc[i]=str[abc[i]]
answered May 8, 2019 at 3:25