Remove whitespaces from Python String

Sujani Thuthilochana
4 min readJul 15, 2022
Remove whitespaces

In computer programming, whitespace is any character or series of characters that represent horizontal or vertical space in typography. Same in the Python, characters that are used for spacing are called whitespace characters. They can be spaces, tabs, newline, carriage return, feed, etc.

Not like most of the other programming languages, Python has its unique syntax : indentation. Though other languages like Java, C# delimite using curly braces or “begin-end” keywords, Python delimite blocks by indentation (whitespace).

In this article, we are gonna discuss the seriousness of whitespace when it uses in a string in Python.

whitespaces

Whitespaces become a common problem when dealing with strings in files or user input strings because Python considers whitespaces as a character which simply means, that even the whitespace can be printed in case you decide to print the string. Otherhand, this whitespace could break the logic of your code and could return a false or misleading output. So when handling strings in Python, it is important to know the ways to remove the whitespaces.

Removing whitespace from a string is known as Trim. There are 3 easy methods to do Trim.

  • strip()
  • lstrip()
  • rstrip()

strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function and it can trim a string by removing all leading and trailing whitespace. Therefore strip() is the safest bet for performing a Python trim.

Syntax:

string.strip("Python Trim is important")

lstrip() in Python is used to trim the string from the left. This means that all whitespaces from the left side of the string will be removed. [lstrip => left removing] This is called removing leading whitespaces.

Syntax:

string.lstrip("Python Trim is important")

rstrip() does the opposite of lstrip(). It removes all the whitespaces from the right side of the string. [rstrip => right removing] This is called removing trailing whitespaces.

Syntax:

string.rstrip("Python Trim is important")

Altogether, the outputs differ like this.

#Here, I've used ◽️ character to represent a whitespace. The length of text will depict how the python has trimmed the whitespaces.text = "  Python Trim  "
#total characters of this text is 15
print(text)
>>◽️◽️Python◽️Trim◽️◽️
print(len(text))
>>15
print(text.strip())
>>Python◽️Trim
print(len(text))
>>11
print(text.lstrip())
>>Python◽️Trim◽️◽️
print(len(text))
>>13
print(text.rstrip())
>>◽️◽️Python◽️Trim
print(len(text))
>>13

Use of replace()

str. replace() Syntax

string.replace(old,new,count)

This can return a copy of the string with all occurrences of substring old replaced by new.

  • If you want to remove all whitespace in a string, the count is 0. So, “◽️”(one whitespace string) can replace by “” (empty string).
#Syntax
print(string.replace(" ",""))
#Example
text = " Python replace "
print(text.replace(" ",""))
>>Pythonreplace#All the leading, trailing and middle whitespaces are removed.
  • If you want to remove all whitespace in a string but keep one space between words, the count is 1.
#Syntax
print(string.replace(" ","",1))
#Example
text = " Python replace "
print(text.replace(" ","",1))
>>Python replace#All the leading, trailing whitespaces are removed. Input has more than 1 middle spaces, output has only 1 middle whitespace.

Use of split()

The split() method splits a string into a list. ! Always one list.

str.split() Syntax

string.split("separator", maxsplit)

Both separator and maxsplit are optional.

  • Separator is for some character that can use for splitting the string. The default separator is whitespace.
  • Maxsplit is for defining how many splits you want to do. The default maxsplit is all occurrences.
text = "   Python split  "
print(text.split())
>>['Python', 'split']text = " Python - strip, replace, split"
print(text.split(","))
>>['Python - strip', 'replace', 'split']text = " strip#replace#split#in Python"
print(text.split("#",2))
>>['strip', 'replace', 'split#in Python']

Use of join with split()

Join does the best in trimming.

Now you know, the best and easiest solution to remove all unnecessary whitespace is to use split() . But it always outputs a list. At this point, join() helps you to take all items in the iterable (list) and combines them into a string using a separator.

textNew = " ".join(string.split())

This may split the string text, and join it with the given separator.

Example

text = "   Python join   "
print(text.split())
>>['Python', 'join']textNew=" ".join(text.split())
print (textNew)
>>Python jointextNew=" : ".join(text.split())
print (textNew)
>>Python : join

These are the techniques and methods that can use for trimming strings in Python. Further, you can use regexes in Python with re.sub() method to do all kinds of trim operations.

Thank you for reading.

--

--