5

I have a string as below ,

val = '["10249/54","10249/147","10249/187","10249/252","10249/336"]'

I need to parse it and take the values after / and put into list as below

['54','147','187','252','336']

My code: [a[a.index('/')+1:] for a in val[1:-1].split(',')]

Output : ['54"', '147"', '187"', '252"', '336"']

It has double quotes also " which is wrong. After i tried as below

c = []
for a in val[1:-1].split(','):
    tmp = a[1:-1]
    c.append(tmp[tmp.index('/')+1:])

Output :

['54', '147', '187', '252', '336']

Is there any better way to do this?

0

4 Answers 4

3

You can do it in one line using literal_eval:

from ast import literal_eval

val = ['54','147','187','252','336']
a = [i.split('/')[-1] for i in literal_eval(val)]

print(a)

Output:

['54', '147', '187', '252', '336']

literal_eval() converts your string into a list, and then i.split('/')[-1] grabs what's after the slash.

Sign up to request clarification or add additional context in comments.

Comments

2

Yeah ... assuming every value has a / like your example, this is superior:

>>> from ast import literal_eval
>>>
>>> val = '["10249/54","10249/147","10249/187","10249/252","10249/336"]'
>>> [int(i.split('/')[1]) for i in literal_eval(val)]
[54, 147, 187, 252, 336]

*edited to insert a forgotten bracket

3 Comments

he wants a list of strings: [str(i.split('/')[1]) for i in literal_eval(val)] swap int with str
I ... guess? I think he wants ints, but he's trying to get strings so he can map(int). In any case, I prefer the answer written this way. Up to the OP to choose.
that's a little overanswering (integer conversion isn't needed), but yeah, probably what OP will ask next :)
2

Try using regular expressions!

You can do it in a single line this way.

import re

val = '["10249/54","10249/147","10249/187","10249/252","10249/336"]'

output = re.findall('/(\d+)', val) # returns a list of all strings that match the pattern

print(output)

Result: ['54', '147', '187', '252', '336']

re.findall generates a new list called with all the matches of the regexp. Check out the docs on regular expressions for more info on this topic.

1 Comment

it works the same in python 2. Hint: it's better to put the result of the print in your answer so others can visually check that it works as needed.
1

You can try json module to convert the string to list

>>> import json
>>> val ='["10249/54","10249/147","10249/187","10249/252","10249/336"]'
>>> list(map(lambda x: x.split('/')[-1], json.loads(val)))
>>> ['54', '147', '187', '252', '336']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.