0

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.

1
  • Did you mean you wanted unique values or only those starting with e-? Commented Mar 27, 2014 at 10:41

3 Answers 3

1

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.

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

3 Comments

Why the assumption that only e- values are to be included?
@MartijnPieters Because of OP's expected output: [100001,100011,100009]
But he could have wanted to get unique values only.
0

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]

1 Comment

@MartijnPieters, Because that is how the OP has specified it in the question
0

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]

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.