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 Display Fibonacci Sequence Using Recursion
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program Read a File Line by Line Into a List
Python Program to Iterate Through Two Lists in Parallel
Convert String to int or Integer in Java
Python String isprintable()
Python Inheritance
Python strftime()
Python strptime()
Python Program to Represent enum
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Program to Parse a String to a Float or Int
Python String isupper()
How to Get Started With Python?
Python Custom Exceptions
Deep Learning in Python - LazyProgrammer
Python bytes()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Java InputStream to String
Converting String to Stream of chars
Python Program to Get File Creation and Modification Date
Python String startswith()
Python Program to Sort Words in Alphabetic Order
Python memoryview()
Python Global Keyword
Python Program to Compute the Power of a Number
Convert char to String in Java
Python Program to Generate a Random Number
Python datetime
Python Set update()
JavaScript Methods of RegExp and String
Python Iterators