Table of Contents
In this example, you will learn to trim whitespace from a String.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Using strip()
my_string = " Python " print(my_string.strip())
Output
Python
strip()
removes the leading and trailing characters including the whitespaces from a string.
However, if you have characters in the string like '\n'
and you want to remove only the whitespaces, you need to specify it explicitly on the strip()
method as shown in the following code.
my_string = " \nPython " print(my_string.strip(" "))
Output
Python
2. Example 2: Using regular expression
import re my_string = " Hello Python " output = re.sub(r'^\s+|\s+$', '', my_string) print(output)
Output
Hello python
In the regex expression, \s
denotes the whitespace and \
is the or operation. +
one or more occurrences of the pattern left to it.
Learn more about regex at Python RegEx.
Related posts:
Python String capitalize()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Java – Generate Random String
Python Recursion
Python String startswith()
Python String format_map()
Python Program to Find Numbers Divisible by Another Number
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Errors and Built-in Exceptions
Python Program to Check If a List is Empty
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python str()
Python String format()
Python reversed()
Python String strip()
Python Program to Find Hash of File
Python String rfind()
Python String isalpha()
Python Program to Get the Class Name of an Instance
Python Dictionary fromkeys()
Python Program to Represent enum
Python Program to Catch Multiple Exceptions in One Line
Python slice()
Python String isprintable()
Python memoryview()
Python input()
Python Program to Find LCM
Debug a JavaMail Program
Python String join()
Python Program to Sort a Dictionary by Value
Python Set symmetric_difference_update()
Python time Module