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 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python abs()
Python Set clear()
Python datetime
Python String index()
Python String join()
Python Program to Get the Full Path of the Current Working Directory
Python Program to Print all Prime Numbers in an Interval
Python String isidentifier()
Generate a String
Python Object Oriented Programming
Python Function Arguments
Python strftime()
Python Program to Remove Punctuations From a String
Python List append()
Check If a String Is Numeric in Java
How to get current date and time in Python?
Python frozenset()
Python Package
Python Program to Represent enum
JavaScript Methods of RegExp and String
Python Program to Find the Square Root
Python Program to Transpose a Matrix
Python Program to Safely Create a Nested Directory
Python Dictionary popitem()
Python RegEx
Python Program to Create a Long Multiline String
Python Program to Convert String to Datetime
Python String count()
Python List count()
Why String is Immutable in Java?
Python Program to Count the Number of Digits Present In a Number