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 Check the File Size
Python Set clear()
Python Program to Make a Simple Calculator
Split a String in Java
Python vars()
How to Remove the Last Character of a String?
Python String isalpha()
Generate a String
Python Program to Check Prime Number
Python Program to Display Fibonacci Sequence Using Recursion
Python Directory and Files Management
Python Program to Print Output Without a Newline
Python Program to Find the Factors of a Number
Python Program to Delete an Element From a Dictionary
Python Shallow Copy and Deep Copy
Python Program to Find Factorial of Number Using Recursion
Converting String to Stream of chars
Python Set difference_update()
Python datetime
Python String lower()
Python String casefold()
Python Set union()
Python Program to Merge Mails
Python Set difference()
Java – Generate Random String
Python Package
Python strftime()
JavaScript Eval: run a code string
Python Program to Capitalize the First Character of a String
Python if...else Statement
Python Anonymous / Lambda Function
Python Program to Safely Create a Nested Directory