[Tutor] How to handle conjunction operators

Peter Otten __peter__ at web.de
Mon Nov 28 12:43:18 CET 2011


surya k wrote:

> Could you please tell me why this isn't working and how can I make it
> possible... Consider this code..

> name = raw_input("Enter your first name:") 
> if name[0] == ("m" or "f" or "b") :
>    rhyme = name[1:]
>    What I want here is.. If the name starts with 'm' or
>    'f' or 'b', The first letter should be removed.But this isn't happening
>    here.

- If you want to make your code bullet-proof you should also consider the 
case where the user enters an empty string.

- You can check if a string starts with a particular string with the 
startswith() method:

>>> "frank".startswith("f")
True

It's not widely known, but the method accepts a tuple since Python 2.5:

>>> "sue".startswith(("m", "f", "b"))
False
>>> "frank".startswith(("m", "f", "b"))
True

The beauty of this approach is that you are not limited to single-char 
prefixes:

>>> "stephen".startswith(("m", "f", "st"))
True




More information about the Tutor mailing list