Thursday, 17 December 2020

Python: Trim white spaces

Below tables summarizes the methods used to trim whitespaces.

 

Method

Description

lstrip()

Strip whitespace from the left side of the string

rstrip()

Strip whitespace from the right side of the string

strip()

Strip whitespace from both left and right side of the string

 

trim.py

message = "    Hello World    "

ltrim_str = message.lstrip()
rtrim_str = message.rstrip()
trim_str = message.strip()

print(f"{ltrim_str}, {rtrim_str}, {trim_str}.")

 

Output

$python3 trim.py 
Hello World    ,     Hello World, Hello World.

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment