Search code examples
pythonpython-3.xstringstrip

How to remove extra spaces from the data which is being entered


I am trying to remove the extra space from the data which is entered as input.

I tried using the .strip() condition but it doesn't remove the extra space of the entered data.

the code I wrote to remove extra space

Data_1 = input("Enter your name:", )
print(Data_1.strip())

Solution

  • These are 3 ways of dealing with spaces you can use according to your needs:

    1- the method you are using

    .strip() method removes whitespaces at the beginning and end of your input string.

    if your input string Data_1 is " john " or "Edward luther " or " Stephanie"

    doing Data_1.strip() returns "john" or "Edward luther" or "Stephanie" with no extra spaces at the beginning and at the end

    2- removing all spaces

    if what you want is remove all the spaces inside a string like "Edward Hamilton luther "

    you can simply use Data_1.replace(" ", ""), that will remove all whitespaces and result in "EdwardHamiltonluther"

    3- removing excessive whitespaces

    if you want to remove excessive whitespaces in a string for example " Edward Hamilton is a nice guy "

    you can use " ".join(Data_1.split())

    it will return "Edward Hamilton is a nice guy"

    try it :

    Data_1 = input("Enter your name:", )
    print(" ".join(Data_1.split()))