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 Find the Square Root
Python Set intersection_update()
Python String join()
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Converting a Stack Trace to a String in Java
Python Program to Check If Two Strings are Anagram
Python bin()
Python Global Keyword
Python Shallow Copy and Deep Copy
Python Function Arguments
Python Program to Merge Two Dictionaries
Python Program to Print Output Without a Newline
Python Program to Add Two Matrices
Python Object Oriented Programming
Python Tuple
Python Program to Check if a Key is Already Present in a Dictionary
Python memoryview()
Python Program to Get the File Name From the File Path
Python ord()
Python vars()
Python Program to Capitalize the First Character of a String
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Differentiate Between del, remove, and pop on a List
Python id()
Convert String to Byte Array and Reverse in Java
Python Program to Copy a File
Python String endswith()
Python Dictionary setdefault()
Python String ljust()
Python String isprintable()
Java InputStream to String
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili