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 sorted()
Python Program to Check the File Size
Python Dictionary clear()
Python Dictionary keys()
Python Dictionary popitem()
Python Program to Compute the Power of a Number
Python Multiple Inheritance
Java String to InputStream
Python Program to Calculate the Area of a Triangle
Convert char to String in Java
Python Program to Find Sum of Natural Numbers Using Recursion
Python Set intersection()
How to Remove the Last Character of a String?
Python datetime
Deep Learning with Python - Francois Cholletf
Python divmod()
Python Machine Learning - Sebastian Raschka
Python sum()
Python Program to Reverse a Number
Python del Statement
Python memoryview()
Python globals()
Convert Character Array to String in Java
Python Program to Remove Punctuations From a String
Python Keywords and Identifiers
Why String is Immutable in Java?
Check if a String is a Palindrome in Java
Python Type Conversion and Type Casting
Python String center()
Python List copy()
Count Occurrences of a Char in a String
Python Program to Generate a Random Number