Python- Look for string only in the beginning of a string

161 Views Asked by At

I am using difflib.Differ() on two lists.

The way Differ works, it appends a + if a line is unique to sequence 2 and a - if a line is unique to sequence 1. It appends this right at the beginning of the sequence.

I want to search for sequences in my list that begin with - or + but only if the string begins with this character as the majority of my sequences have these characters in other places within the string.

In the code snippet below, diff_list is the list. I want it to check for a + or - in the very first place in the string value of every sequence in this list:

for x in diff_list:
    if "+" or "-" in x[0]:
        print x

This output seems to print all of the lines even those that don't begin with - or +

1

There are 1 best solutions below

2
moorecm On BEST ANSWER

Did you try startswith?

s = '+asdf'  # sample data

if s.startswith('+') or s.startswith('-'):
    pass  # do work here

Docs: https://docs.python.org/3.4/library/stdtypes.html#str.startswith