Online Tutorials & Training Materials | STechies.com
Register Login

Removing White Space in Python String

|| 0

Removing White Space in Python String
Stechies

There are two ways using functions and program:

Using Functions 

Here I try to show the how to remove white space leading , trailing and duplicate spaces in python using function lstrip() , rstrip() and strip() with an example for each.

Remove all the spaces in python
Remove (strip) white spaces from start and end of the string.
Remove Duplicate Spaces in Python

Example code 

Remove Space at the start of the string in Python:

## Removing the Leading spaces in python

string1 = "   This is test string to strip leading space"
print string1
print string1.lstrip()

Here lstrip() function will remove leading space output would be

Out Put: This is test string to strip leading space

Removing trailing Space of the string 

stringT = "This is test string to strip leading space    "
print stringT
print stringT.rstrip()

Here rstrip() function will remove Trailing space output would be

Orignal: "This is test string to strip leading space        "

Out Put: This is test string to strip Trailing space

Remove Space at Leading and Trailing or Staring and End of a String

stringTE = "   This is Test String to strip leading and trailing space  "
print stringTE
print stringTE.strip()

strip() function in the above example strips, both leading and trailing space so the output will be 

   This is Test String to strip leading and trailing space  
This is Test String to strip leading and trailing space

Remove or strip all the spaces in python:

stringAll = "    This is string for test all spaces    "
print stringAll
print stringAll.replace(" ", "")

Will removes all the spaces in the string. So the output will be

OutPut:

    This is string for test all spaces    
Thisisstringfortestallspaces

 

Remove unnecessary Duplicated Space in String

import re
stringDub = " This is     Test String    to test    duplicate spaces  "
print stringDub
print re.sub(' +', ' ',stringDub)

to remove the unnecessary duplicate spaces in string.

sub() function: ab.sub() function takes the stringDub argument and replaces one or more space with single space as shown above so the output.

This is     Test String    to test    duplicate spaces  
 This is Test String to test duplicate spaces 

2.Using Program

# Python program to remove punctuation from a given string

punctuation = '''!()-[]{};:'",<>./?@#$%^&*_~'''
string = "Welcome???@@##$ to#$% world %$^of$%^& new world"

# traverse the given string and if any punctuation
# marks occur replace it with null
for x in string.lower():
    if x in punctuation:
        string = string.replace(x, "")

# Print string without punctuation
print(string)

OutPut

Welcome to world of new world

 


Related Articles