Search code examples
pythonpython-3.xstartswithends-with

Shortest code for printing line startswith ['a', 'b'] and endswith ['y', 'z'] Python 3


For an assignment I have to print lines from a text that start with "W" and "Z" and end in "n" and "t" (so W-n, W-t, Z-n, Z-t combo's). I have a code now that works, but it seems a bit long and I was wondering if there is a way to shorten it?

This is the code:

import sys

def main():

    for line in sys.stdin:
        line = line.rstrip()
        if line.startswith("W") and line.endswith("n"):
                print(line)
        if line.startswith("W") and line.endswith("t"):
                print(line)
        if line.startswith("Z") and line.endswith("n"):
                print(line)
        if line.startswith("Z") and line.endswith("t"):
                print(line)

main()

As I said, it works, but it seems a bit elaborate. Any tips on how to shorten?

I tried line.startswith("Z","W") and line.endswith("t","n") but I get a Type Error (all slice indices must be integers or None or have an __index__method).


Solution

  • You could do this:

    line = line.rstrip()
    if line and line[0] in "WZ" and line[-1] in "nt":
        print(line)
    

    Or use regular expressions:

    import re 
    # ...
    if re.match(r'^[WZ].*[nt]$', line):
        print(line)
    
    # ^ beginning of string
    # $ end of string
    # [WX] matches W or X
    # .*  any character 0 or more times
    

    See the docs on Python regex syntax.