close

How to remove Extra WhiteSpace From String in Python

Sometimes you have extra white spaces in your string. Sometomes these white spaces become unnecessary special when you are working on a operation of string or a bigger application program. these unnecessary spaces can be removed by some methods. so lets learn How to remove Extra WhiteSpace From String in Python.

How to remove Extra WhiteSpace From String in Python

So here we are learning about of to remove the white spaces between of the string. another one is leading of the string and trailing of the string. So we will learn about to remove the space between of string, before the string and after the string.

  1. remove Extra WhiteSpace From String in Python

    to remove Extra WhiteSpace From String in Python just use replace. By using replace you can remove the extra which spaces between of string. lets learn how this work.
    mystr = ' su n da y' print(mystr.replace(" ", "")) Output: sunday

  2. How to remove Extra WhiteSpace From String in Python

    to remove Extra WhiteSpace From String in Python just use join and split.By using join and split you can remove white spcaes very easily. lets learn this by given below example: mystr = ' su n da y' print("".join(mystr.split())) Output : sunday

Method 1: use replace

To remove the white spaces between of the string you can use this method. here we are using replace() to remove the spaces. lets learn this how it works.

mystr = ' su n da y'
print(mystr.replace(" ", ""))

Output:

sunday

Method 2: use join and split

By using join and split you can remove white spcaes very easily. you have the white spaces between of the tring then use thios method. It will completely remove all the white spaces between of the string. you can use join () and split() to remove the white spaces.

mystr = ' su n da y'
print("".join(mystr.split())) 

Output :

sunday

Method 3: use str.lstrip() for remove leading white space

Sometimes in string you have some extra spaces at leading position which you want to remove. there you can use str.lstrip() and can easily remove the leading white space. You will better understand it by given example.

mystr="   Hello   world  "
print (mystr.lstrip())

Output :

Hello   world  

Method 4: use str.rstrip() for remove trailing white space

This method only use for remove trailing white space. It will remove only trailing white space. Just use str.rstrip() and you can remove the space behind of the string which is completly unnecessary. So lets see it by example.

mystr="   Hello   world  "
print (mystr.rstrip())

Output :

   Hello   world

Conlusion

Hope all 6 Method Are Useful For You. Comment Below Which Method You Used To Convert String To Datetime In Python. Thank You.

Also Read

Leave a Comment