You are currently viewing Trim Whitespace from a String in Python?

How do I trim whitespace from the beginning, end, or both sides of a string in Python? Strings can sometimes contain unwanted whitespace characters at the beginning, end, or both sides, which can lead to errors. In this article, we will learn various methods for trimming whitespace from strings in Python.

Advertisements

We will discuss how to remove whitespace from the beginning, end, and both sides of a string using built-in methods such as strip(), lstrip(), and rstrip(), as well as using regular expressions and the join() and split() methods with examples.

1. Quick Examples – Trim Whitespace from a String

These quick examples below will give you a high-level idea of how to trim whitespace from a string in Python. Let’s take a look at some quick examples and we will discuss each of them in detail later on:


# Quick Examples to Trim Whitespaces from String
sample_string = "   Spark By Examples   "

# Removing all Whitespaces from String
no_whitespace_string = sample_string.replace(" ", "")


# split() - Trims characters from both ends
trimmed_string = sample_string.split()[0]


# rstrip() - Trims characters from the right side
trimmed_string = sample_string.rstrip()


# lstrip() - Trims characters from the left side of a string
trimmed_string = sample_string.lstrip()


# Using a regular expression
import re
trimmed_string = re.sub(r'\s+', '', sample_string)

2. Trim all Whitespaces from String

To trim all whitespaces from a string you can use the Python replace() function, This replaces all occurrences of spaces from the String not just those at the beginning or end of the string. To achieve this, you can use the replace() method to replace all occurrences of whitespace with an empty string.

See the below example:


# Remove all whitespaces
sample_string = "   Spark By Examples   "

# Removing all whitespace characters from the string
no_whitespace_string = sample_string.replace(" ", "")
print(no_whitespace_string)  

# Output: 
# "SparkByExamples"

The replace() method creates a new string and returns it, rather than modifying the original string in place. if you want to modify the original string, you’ll need to assign the result of the replace() method back to the original string variable.

If you want to remove the new line and tabs from the string you can still use the replace() method.


# Removde newlines, whitespaces and tabs
sample_string = "  \Spark\t By Example  \t\n"

# Remove whitespaces
no_whitespace_str = sample_string.replace(" ", "")

# Remove newlines
no_newline_str = sample_string.replace("\n", "")

# Remove tabs
no_tab_str= sample_string.replace("\t", "")

3. strip() – Trims Characters from Both Ends

The strip() method trims leading and trailing characters from a string in Python. By default, the strip() method trim whitespace characters, such as spaces, tabs, and newlines, from both ends of the string.


# Removing whitespace characters from both ends of the string
no_whitespace_string = sample_string.strip()
print(no_whitespace_string)  

# Output: 
# "Spark By Examples"

If you want to remove specific characters from both ends of the string, you can pass them as an argument to the strip() method.


# Remove (!) character
sample_string = "Spark By Examples!"

# Removing exclamation marks from both ends of the string
no_exclamation_marks_string = sample_string.strip("!")
print(no_exclamation_marks_string)  
# Output: 
# "Spark By Examples"

4. rstrip() – Trim Spaces from the Right Side

You can use the the rstrip() method to remove trailing white space characters from a string, that is, characters at the end of the string. By default, the rstrip() method removes whitespace characters, such as spaces, tabs, and newlines, from the right side of the string.


# Removing whitespace characters from the right side of the string
no_trailing_whitespace_string = sample_string.rstrip()
print(no_trailing_whitespace_string) 

# Output: 
# "   Spark By Examples"

If you want to remove specific characters from the right side of the string, you can pass them as an argument to the rstrip() method.

5. lstrip() – Trims Spaces from the Left Side of a string

The lstrip() method removes any leading white space characters (characters at the beginning) from a string. By default, it removes whitespace characters such as spaces, tabs, and newlines.


# Use lstrip() to remove whitespaces
trimmed_text = sample_string.lstrip()

print(trimmed_text) 

# Output: 
# "Spark By Examples "

6. Using a regular expression

Regular expressions allow you to search for and manipulate strings based on patterns, rather than just specific characters or substrings. You can use regular expressions to trim whitespace from a string, as well as perform many other types of text manipulation.


# Using regular expression
import re

trimmed_text = re.sub(r"\s+", "", sample_string)
print(trimmed_text) 

# Output: 
# "SparkByExamples "

The re.sub() function is used to replace all occurrences of the pattern with a replacement string. In this case, the replacement string is an empty string, effectively removing all whitespace characters.

7. Using the join() and split()

Finally, you can also use the Python join() and split() methods together to trim white spaces from the String. The join() method is used to join a list of strings into a single string, using a specified delimiter. The split() method is used to split a string into a list of substrings, using a specified delimiter.


# Using Join and Split method to remove whitespaces
sample_string = "   Spark By Examples   "

trimmed_text = ''.join(sample_string.split())
print(trimmed_text)

# Output: 
# "SparkByExamples "

8. Summary and Conclusion

In this article, you have learned how to trim whitespace from a Python string using different methods to trim the whitespace from the beginning, end, and both sides of a string. I hope this article was helpful. Let me know if you have any questions.

Happy Coding!