Search code examples
pythoninputspacestartswith

How to delete space in the input in Python


I am writing a program where the user is asked to type in his name.

If the name starts with a, b or c, the program should print ("Your name starts with a, b or c").

Unfortunately if the user starts by typing in a space and then typing his name the program thinks the name starts with a space and it automatically prints "Your name doesn't start with a, b or c" even if the name starts with these letters.

I want to delete the space in the input now so this problem doesn't occure any longer.

So far I've tried if name.startswith((" ")): name.replace(" ", "") Thanks for any help!

name = input("Hi, who are you?")
if name.startswith((" ")):
    name.replace(" ", "")

if name.startswith(('a', 'b', 'c')):
    print("Your name starts with a, b or c")
    print(name)
else:
    print("Your name doesn't start with a, b or c")
    print(name)

Solution

  • String are imutable. No operation on a string will ever change this string

    name.replace(" ", "") do not modify namebut return a new string and let name unchange

    So you can write

    new_name = name.replace(" ", "")
    

    but you can also write

    name = name.replace(" ", "")
    

    In this case, the original string is not modified. But it's name is reused to receive the result of name.replace(" ", "")

    Wich writing is the best depend on who you ask. I prefer the second one.