What is the easiest way to get all strings that do not start with a character? What is the easiest way to get all strings that do not start with a character? python python

What is the easiest way to get all strings that do not start with a character?


Use generator expressions, the best way I think.

for line in (line for line in x if not line.startswith('?')):    DO_STUFF

Or your way:

for line in x:    if line.startswith("?"):        continue    DO_STUFF

Or:

for line in x:    if not line.startswith("?"):        DO_STUFF

It is really up to your programming style. I prefer the first one, but maybe second one seems simplier. But I don't really like third one because of a lot of indentation.


Here is a nice one-liner, which is very close to natural language.

String definition:

StringList = [ '__one', '__two', 'three', 'four' ]

Code which performs the deed:

BetterStringList = [ p for p in StringList if not(p.startswith('__'))]


Something like this is probably what you're after:

with open('myfile.txt') as fh:  for line in fh:    if line[0] != '?': # strings can be accessed like lists - they're immutable sequences.      continue    # All of the processing here when lines don't start with question marks.