Reputation: 359
I have a string like:
u'c-100001,e-100001,e-100011,e-100009'
I want to get value like
[100001,100011,100009]
I tried:
l = note_to.split('-')
k = length(l)
j=[]
for i in (0,k):
if k!==0 & k%2!= 0:
j.append(l[i])
I mean I used loop.
Upvotes: 0
Views: 70
Reputation: 1121904
Split your string on the comma and use a list comprehension:
[int(el[2:]) for el in note_to.split(',') if el.startswith('e-')]
I'm assuming you wanted to only get values that start with e-
here; you need to clarify your question if you wanted something different.
Because we already determined that the element starts with e-
, getting the integer value is as simple as skipping the first 2 characters.
Demo:
>>> note_to = u'c-100001,e-100001,e-100011,e-100009'
>>> [int(el[2:]) for el in note_to.split(',') if el.startswith('e-')]
[100001, 100011, 100009]
If you wanted to get unique values only, and order doesn't matter, use a set, and use str.rpartition()
to split off the starting string (which could be longer than 2 characters or missing altogether, perhaps):
set(int(el.rpartition('-')[-1]) for el in note_to.split(','))
You can always turn that back into a list, based on your exact needs.
Demo:
>>> set(int(el.rpartition('-')[-1]) for el in note_to.split(','))
set([100001, 100011, 100009])
>>> list(set(int(el.rpartition('-')[-1]) for el in note_to.split(',')))
[100001, 100011, 100009]
Upvotes: 0
Reputation: 250951
Use a list comprehension with str.startswith
and str.split
:
>>> s = u'c-100001,e-100001,e-100011,e-100009'
>>> [int(x.split('-')[1]) for x in s.split(',') if x.startswith('e-')]
[100001, 100011, 100009]
If you want all the items not just that start with e-
then remove the if x.startswith('e-')
part.
>>> [int(x.split('-')[1]) for x in s.split(',')]
[100001, 100001, 100011, 100009]
In you want only unique items then pass the list to a set()
or use set with a generator expression.
Upvotes: 1
Reputation: 32189
You can do it as follows:
string = 'c-100001,e-100001,e-100011,e-100009'
your_list = string.split(',e-')[1:]
>>> your_list
[100001,100011,100009]
Upvotes: 0