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 rsplit()
Python List count()
Python Tuple index()
Python String encode()
Python divmod()
Python Program to Generate a Random Number
Python Get Current time
Python String rindex()
Python Program to Convert Kilometers to Miles
Map to String Conversion in Java
Python Program to Print the Fibonacci sequence
Python List extend()
Python reversed()
Python List
Python Program Read a File Line by Line Into a List
Python repr()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python String split()
Python Set intersection()
String Processing with Apache Commons Lang 3
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python String isdigit()
Python Dictionary copy()
Python enumerate()
Python Program to Find the Square Root
Python Global Keyword
Python Functions
Python Program to Extract Extension From the File Name
Python Program to Find Numbers Divisible by Another Number
Python Keywords and Identifiers
Python Exception Handling Using try, except and finally statement