How to Remove Whitespace from a String in Python?

Spread the love

Problem –

You want to remove whitespace from a string in python.

Solution –

In this post you will learn –

  1. How to remove whitespace from the beginning of a string in python
  2. How to remove whitespace from the end of a string in python
  3. How to remove whitespaces from both the beginning and end of a string in python
  4. How to Remove all whitespaces from a string in python

Remove Whitespace from the beginning of a string in python –

To remove whitespace from the beginning of a string in python, you can use the str.lstrip() method in python.

Syntax –

str.lstrip([chars])

chars( optional) – Characters to be removed from the beginning of the string. By default if no characters are provided then python removes the all the leading white spaces from the left.

In [1]: string1 = '    python   ' 

In [2]: string1.lstrip()
Out[2]: 'python   '

Remove Whitespace from the end of a string in python –

To remove whitespace from the end of a string in python you can use the str.rstrip() method in python.

Syntax –

str.rstrip([chars])

Example –

In [1]: string1 = '     Python      '

In [2]: string1.rstrip()
Out[2]: '     Python'

Remove Whitespaces from both the beginning and end of the string in python –

To remove whitespaces from both the beginning and end of the string in python, you can use the str.strip() method.

syntax –

str.strip([chars])

Example –

In [1]: string1 = '    sirens of the sea    '

In [2]: string1.strip()
Out[2]: 'sirens of the sea'

Remove all whitespaces from the string in python –

To remove all whitespaces from the string in python, you can use the str.replace() method.

syntax –

string.replace(old, new, [, count])

old – old substring you want to replace

new – new substring with which you want to replace

count (optional) – the number of times you want to replace the old substring with the new one.

Example –

In [1]: string = "sirens of the sea"

In [2]: string.replace(" ", "")
Out[2]: 'sirensofthesea'

Rating: 1 out of 5.

Leave a Reply