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 Program to Find the Largest Among Three Numbers
Python Functions
Java String Conversions
Java InputStream to String
Python Program to Find Numbers Divisible by Another Number
Python String center()
Python Program to Count the Number of Occurrence of a Character in String
Python Package
Java InputStream to String
Python dict()
Python Program to Check Leap Year
Python Program to Count the Occurrence of an Item in a List
Python Program to Remove Duplicate Element From a List
Python Program to Split a List Into Evenly Sized Chunks
Python set()
Python min()
Deep Learning with Python - Francois Chollet
Java – Generate Random String
Python Program to Shuffle Deck of Cards
Python Matrices and NumPy Arrays
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Machine Learning - Sebastian Raschka
Python Program to Measure the Elapsed Time in Python
Python Operator Overloading
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python sleep()
Format ZonedDateTime to String
Python Modules
Java – String to Reader
Python File I/O Operation
Python Dictionary pop()
Python Program to Solve Quadratic Equation