Skip to content
Advertisement

How to select the first character on a string in python then use that first character in an if statement

def are_you_playing_banjo(name):
    first_char = name[0]
    if first_char != "r" or "R":
        outcome = name + " does not play banjo"
    else:
        outcome = name + " plays banjo"
    return outcome

p = are_you_playing_banjo("rick")
print (p)

**This should print “{name} plays banjo” because the name starts with “r” and I suspect that there is something wrong with how I selected the first character of the string and used it in an if statement. **

Advertisement

Answer

Python has a string method startswith() which will do what you need.

Replace

first_char = name[0]
if first_char.....

With a single if statement

if not name.lower().startswith("r"):
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement