0

My current code:

>>> sent=['attachment', '(1.', '=', '+EDT)', 'Details'] >>> [w[1:] for w in sent if w.startswith(('(', '+'))]+[w for w in sent if not w.startswith(('(', '+'))] 

output:

['1.', 'EDT)', 'attachment', '=', 'Details'] 

I want it like this:

['attachment','1.', '=','EDT)', 'Details'] 

maintaining the original order.

I don't want to use re.replace, I just want to use w.startswith().

3
  • If you describe in plain language what you want to do, it will be easier to help you. But anyway, str.lstrip() seems to be what you want. Commented Aug 1, 2015 at 14:44
  • str.lstrip() can't help me in this situation :'( Commented Aug 1, 2015 at 14:48
  • thank you so much DSM. this is great. Commented Aug 1, 2015 at 15:01

2 Answers 2

2

To use startswith() while maintaining the original order you need to perform the operation inside one list comprehension. We can do that using a conditional expression:

sent = ['attachment', '(1.', '=', '+EDT)', 'Details'] print([w[1:] if w.startswith(('(', '+')) else w for w in sent]) 

output

['attachment', '1.', '=', 'EDT)', 'Details'] 
Sign up to request clarification or add additional context in comments.

Comments

1

Your code does not work since it is building 2 lists; the first one contains those which start with + or (, and the second one those which don't; these are then catenated in order.


Your code fixed and using a conditional expression properly would read

>>> sent = ['attachment', '(1.', '=', '+EDT)', 'Details'] >>> [ w[1:] if w.startswith(('(', '+')) else w for w in sent ] ['attachment', '1.', '=', 'EDT)', 'Details'] 

However a better and more powerful option would be to use re.sub here

>>> import re >>> sent = ['attachment', '(1.', '=', '+EDT)', 'Details'] >>> [ re.sub(r'^[+(]', '', w) for w in sent ] ['attachment', '1.', '=','EDT)', 'Details'] 

The regular expression ^[+(] matches the beginning of string followed by exactly 1 + or (; whatever is matched is replaced with an empty string ''.


On the other hand if you really want removing all leading ( and + characters, no matter how many, use the .lstrip:

>>> sent = ['attachment', '(1.', '=', '+EDT)', 'Details'] >>> [ w.lstrip('+(') for w in sent ] ['attachment', '1.', '=', 'EDT)', 'Details'] 

This will also replace +(++++((((foo with foo which might or might not be what you wanted.

1 Comment

Note that the OP doesn't want to import the re module for this - they want to do it with built-in methods. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.