Python Program to Remove Spaces from String
This article contains multiple programs in Python that removes spaces from a string, entered by user at run-time of the program. Here are the list of programs covered by this article:
- Remove all spaces from a given string using inbuilt function in Python
- Remove all spaces from a given string without using inbuilt function in Python
- Remove spaces from both the end of the string in Python
Python Remove Spaces from String using replace() Method
The question is, write a Python program to remove all spaces from a string. The string must be received by user at run-time. The program given below is its answer:
print("Enter the String: ", end="") str = input() str = str.replace(" ", "") print("\nString without Space:", str)
The snapshot given below shows the sample run of above program, with user input codes cracker . com as string:
Python Remove Spaces from String without using replace() Method
This program does the same job as of previous program. The only difference is, this program is created without using an inbuilt function named replace()
print("Enter the String: ", end="") str = input() newstr = "" for i in range(len(str)): ch = str[i] if ch != ' ': newstr = newstr + ch str = newstr print("\nString without Space:", str)
This program produces same output as of previous program.
Remove Spaces from Both Ends of String in Python
This is the last program of this article, created to remove only leading and trailing spaces from a given string. That is, the program removes whitespace from start and end of the string. Basically this program removes spaces from both the ends of the string.
print("Enter the String: ", end="") str = input() index = 0 strLen = len(str) for i in range(strLen): if str[i] == ' ': continue else: index = i break newStr = "" for i in range(index, strLen): newStr = newStr + str[i] newStrLen = len(newStr) for i in range(newStrLen-1, 0, -1): if newStr[i] == ' ': continue else: index = i break resStr = "" for i in range(index+1): resStr = resStr + newStr[i] str = resStr print("\nString without leading and trailing spaces:", str)
Sample run of above Python program with string input that contains leading and trailing spaces, is shown in the snapshot given below:
In the new string, the removed leading spaces can easily be spotted, but it is not possible to spot the removed trailing spaces. Therefore replace the following statements, from the above program:
str = resStr print("\nString without leading and trailing spaces:", str
with these statements:
print("\nOriginal String: \"", str, "\"", sep="") str = resStr print("New String: \"", str, "\"", sep="")
Now the sample run with another user input as string with spaces available at both ends, looks like:
Same Program in Other Languages
« Previous Program Next Program »
Liked this post? Share it!