How do I trim whitespace from a string in Python

Pybeginner
By -
0

 



When working with Python strings, a very common question is how to trim whitespace from a string. Whitespace characters are space (), tab (\t), newline (\n) and return characters  (\r)


Here are 3 different methods to trim whitespace from a string in Python.


Remove whitespace from right and left:


Use the method str.strip() to remove white space characters from the beginning and end of a string.




# original string

my_string = '  Hello  '  

 

# cutting spaces in the string

new_string = my_string.strip()    

 

print(new_string)



Remove whitespace from left side :

Leading whitespace characters are the whitespace characters at the beginning of a string. To remove them, use the str.lstrip() method.



# original string

my_string = '  Hello  '  

 

# cutting spaces in the string

new_string = my_string.lstrip()    

 

print(new_string)


Remove whitespace from right side

Trailing whitespace characters are the whitespace characters at the end of a string. To remove them, use the str.rstrip() method.



# original string

my_string = '  Hello  '  

 

# cutting spaces in the string

new_string = my_string.rstrip() 


Tags:

Post a Comment

0Comments

Post a Comment (0)