AppDividend
Latest Code Tutorials

How to Trim Whitespace in Python

0

Python string is an immutable object. String literals are surrounded by either single quotations or double quotations. To display string literal, use the print() method.

Trim Whitespace in Python

To trim whitespace in Python, use one of the following various ways.

  1. Python strip()
  2. Python replace()
  3. String join() with split()
  4. Python translate()

Python strip()

String strip() in Python is an inbuilt method that will remove leading and trailing whitespaces. If you want to remove the leading whitespace of string or trailing whitespace of string, use lstrip() or rstrip() methods.

# app.py

str = "      Phew    kung paw    "

print(str)

print(str.strip())

Output

python3 app.py
      Phew    kung paw
Phew    kung paw

You can see from the output that the strip() function removes the spaces from the left and right side of the string, but it will not remove the spaces between the characters of the string.

Python lstrip()

The lstrip() is an inbuilt Python function that removes any leading characters (space is the default leading character to remove).

# app.py

str = "      Phew    kung paw    "

print(str)

print(str.lstrip())

Output

      Phew    kung paw
Phew    kung paw

Python rstrip()

The rstrip() is an inbuilt Python function that removes any trailing characters.

# app.py

str = "     Phew    kung paw    "

print(str)

print(str.rstrip())

Output

     Phew    kung paw
     Phew    kung paw

String replace()

The string replace() function replaces the whitespace with nothing, and hence it will remove the whitespace. It can even remove the whitespace between the characters of the string as well.

# app.py

str = "     Phew    kung paw    "

print(str)

print(str.replace(" ", ""))

Output

     Phew    kung paw
Phewkungpaw

String join() with split()

To remove all the duplicate whitespaces and newline characters in Python, use the combination of string join() and string split() method.

Python string join() method returns the string concatenated with the items of the iterable.

Python string split() method splits the string into the list.

So, first, we split the string and then join the string.

# app.py

str = "     Phew    kung paw    "

print(str)

print(" ".join(str.split()))

Output

     Phew    kung paw
Phew kung paw

Python translate()

To remove all the whitespaces and newline characters in Python, you can also use the string translate() function.

# app.py

import string

str = "     Phew    kung paw    "

print(str)

print(str.translate({ord(c): None for c in string.whitespace}))

Output

     Phew    kung paw
Phewkungpaw

You can see that it has removed all the whitespaces, leading, trailing, and in-between spaces.

That is it for this tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.