How To Remove Spaces From A String In Python

Share This Post

In Python, there are several methods for removing spaces from a string. This article aims to give a quick overview of the many functions available for removing whitespace from a string so let’s go and remove spaces from a string in python.

Remove Spaces from a String in Python

We can’t change the value of a Python String because it’s immutable. Any function that manipulates string values returns a new string, which must be explicitly assigned to the string otherwise the string value will remain unchanged.

Let’s imagine we have the following sample string: s = ‘  Hello  World   From Pankaj \t\n\r\tHi There

There are many types of whitespaces as well as newline characters in this string. Let’s have a look at some of the functions that can be used to eliminate spaces. strip() \sPython The strip() function removes leading and trailing whitespaces from a string.


s.strip()

'Hello World From Pankaj \t\n\r\tHi There'

Instead, use the lstrip() or rstrip() functions to remove only leading or trailing spaces.


replace()

To eliminate all whitespaces from the string, we can use replace(). Whitespace between words will also be removed by this function.


s.replace()

'HelloWorldFromPankaj\t\n\r\tHiThere'

join() with split()

You can use the join() function in conjunction with the string split() function to remove all duplicate whitespaces and newline characters.


translate()

The string translate() function can be used to remove all whitespaces and newline characters from a string.

Read More: How To Split A-List In Python?

spot_img

Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img