Remove spaces from string Python
In this post, you will learn how to remove spaces from a string using the Python programming language. In the development process, sometimes we want to remove all occurrences of white-space from a string. There are different ways to remove spaces from a string. Here, we have mentioned most of them.
Python remove spaces from string using replace() function
The replace() method of Python returns a copy of the string where all occurrences of a substring are replaced with another substring. The syntax of the replace() method-
string.replace(old, new, count)
Here, old is the string you search for, new is the string to replace the old value, and count is the number of times you want to replace the old substring with the new substring. In the given example, we have removed spaces from the string.
txt = "e tuto rials point"
x = txt.replace(" ", "")
print("Original string:", txt)
print("New string:", x)
Output of the above code-
Original string: e tuto rials point
New string: etutorialspoint
Python remove spaces from string using translate() function
The translate() function of Python enables us to map the characters in a string, replacing those in one table by those in another. And, the 'maketrans()' function in the string module makes it easy to create the mapping table. The syntax of the Python translate() method-
str.translate(table[, deletechars])
Here, the table is the required parameter. It is a translation table, created by using the maketrans() function, and deletechars is the list of characters removed from the string. In the given example, the translate() function removes all of the white-spaces from the string and results in a compact string as an output.
import string
# initializing string
txt = " Welcome to etutorials point "
# printing original string
print ("Original String - " + txt)
print("New String - "+ txt.translate({ord(c): None for c in string.whitespace}))
Output of the above code -
Original String - Welcome to etutorials point
New String - Welcometoetutorialspoint
Python remove spaces from string using join() with split()
The join() method is a Python string method and returns a string by joining all the elements of an iterable, separated by a string separator. We can use this with the split() method to remove the unwanted spaces.
def removespaces(string):
return "".join(string.split())
string = ' e tuto rials p o i n t '
# printing original string
print ("Original String - ", string)
print("New String - ", removespaces(string))
Output of the above code -
Original String - e tuto rials p o i n t
New String - etutorialspoint
Python remove spaces from string using Regex
Regular expression is useful for flexible string matching. It provides patterns or a sequence of characters for matching text and defining search patterns. Python provides a re module that supports the use of regex in Python. We can use a regular expression to match whitespace and eliminate them using the re.sub() function.
import re
s = ' Welcome to \t\n\r\tetutorialspoint '
print('Original String:', s)
print('New String:\n', re.sub(r"\s+", "", s), sep='')
Output of the above code-
Original String: Welcome to
etutorialspoint
New String:
Welcometoetutorialspoint
Python remove spaces from string using lstrip() function
Python String lstrip() method returns a copy of the string with leading characters removed.
string = " Welcome to etutorialspoint"
string_new = string.lstrip()
print(string_new)
Output of the above code:
Welcome to etutorialspoint
Python remove spaces from string using rstrip() function
Python String rstrip() method returns a copy of the string by removing the trailing whitespace.
string = "Welcome to etutorialspoint "
string_new = string.rstrip()
print(string_new)
Output of the above code:
Welcome to etutorialspoint
Python remove spaces from string using isspace() method
Python isspace() method is used to check for space in the string. It returns true if there are only whitespace characters in the string. The in operator in Python checks whether a specified value is a constituent element of a sequence, like a list. The not in operator in Python works exactly the opposite way as the in operator works. In the given program, we used both operators with isspace() to remove spaces from a string.
def removeSpace(string):
result=""
for s in string:
if(not s.isspace()):
result+=s
return result
# Driver Program
string = ' e t u t o r i a l s '
print(removeSpace(string))
Output of the above code:
etutorials
Related Articles
Count occurrences of each character in string Python
Count vowels in a string python
Python remove punctuation from string
Python multiline string
Count consonants in a string Python
Convert string to list Python
Convert string to int python
Python program to reverse a string
Python String Exercise
Python remove punctuation from string
Remove spaces from string Python
Python program to sort words in alphabetical order
Count consonants in a string Python
Pandas string to datetime
Python split string by comma
Convert string to int python
Permutation of string in Python
Python split multiple delimiters
Check if two strings are anagrams Python