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 Create a Countdown Timer
Python Program to Find HCF or GCD
Python String expandtabs()
Python any()
Python Program to Check if a Number is Odd or Even
Python String lstrip()
Deep Learning with Python - Francois Chollet
Python sleep()
Python Program to Differentiate Between type() and isinstance()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python all()
Python String rstrip()
Python String isidentifier()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Namespace and Scope
Python Program to Create a Long Multiline String
Python locals()
Python Directory and Files Management
Python bytes()
Python Program to Measure the Elapsed Time in Python
Python break and continue
Python List Comprehension
Convert String to Byte Array and Reverse in Java
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Iterators
Python Program to Extract Extension From the File Name
Python Program to Print Output Without a Newline
Python map()
Python String islower()
Python Type Conversion and Type Casting
Python Set difference_update()
Python Machine Learning Eqution Reference - Sebastian Raschka