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 hash()
Python Program to Parse a String to a Float or Int
Python Global, Local and Nonlocal variables
Python Program to Find the Size (Resolution) of a Image
Python String split()
Python List count()
Python abs()
Python Program to Print the Fibonacci sequence
Python del Statement
Python Functions
Python @property decorator
Python Set update()
Python Program to Extract Extension From the File Name
Python Program to Check Leap Year
Python List insert()
CharSequence vs. String in Java
Python Program to Find All File with .txt Extension Present Inside a Directory
Python strptime()
Python Program to Find the Square Root
Python Program to Get the Last Element of the List
Python pow()
Python eval()
Python String join()
Python Program to Find Numbers Divisible by Another Number
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python List remove()
Python String isalnum()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Check If a List is Empty
Python Program to Multiply Two Matrices
Python Set intersection()
Python Program to Check if a Number is Positive, Negative or 0