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 datetime
JavaScript Eval: run a code string
Python pass statement
Python String translate()
Python min()
Python Set isdisjoint()
Python callable()
Python Program to Find Sum of Natural Numbers Using Recursion
Python dict()
Check if a String is a Palindrome in Java
Python Program to Extract Extension From the File Name
Python Program to Print Colored Text to the Terminal
Python String isprintable()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Exception Handling Using try, except and finally statement
Python Data Types
Python String rstrip()
Python help()
Python max()
Python List clear()
Python Directory and Files Management
Python Program to Get the File Name From the File Path
Python String upper()
Python String isdecimal()
Python Tuple index()
Python id()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python bool()
Python Function Arguments
Python round()
Python String splitlines()