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:
Adding a Newline Character to a String in Java
Python Program to Find Sum of Natural Numbers Using Recursion
Python Program to Differentiate Between del, remove, and pop on a List
Python Program to Transpose a Matrix
Python String rindex()
Python RegEx
Python Shallow Copy and Deep Copy
Python Program to Convert Kilometers to Miles
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Check Whether a String is Palindrome or Not
Python int()
Python setattr()
Python String capitalize()
Python map()
Python Package
Python Program to Generate a Random Number
Machine Learning with Python for everyone - Mark E.Fenner
Python Program to Find Armstrong Number in an Interval
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Program to Get the Last Element of the List
Python Multiple Inheritance
Python classmethod()
Python Program to Check Armstrong Number
Python String format()
Java InputStream to String
Python Program to Make a Simple Calculator
Python Program to Swap Two Variables
Python List copy()
Python hasattr()
Intelligent Projects Using Python - Santanu Pattanayak
Python set()
Python Inheritance