python

Python Trim String Example | rstrip(), lstrip(), strip() Function


Sometimes we may need to Trim String, whitespace characters from the left side, right side, or both sides of a string.

For this purpose Python provides three methods to Trim String.

  1. The strip() string method will return a new string without any whitespace characters at the beginning or end.
  2. The lstrip()  method will remove whitespace characters from the left side
  3. rstrip() method will remove whitespace characters from the Right side

Strip() example

code

code = '    Code, source    '
code.strip()
print(f'After Trimming Whitespaces String =\'{code.strip()}\'')

output

After Trimming Whitespaces String ='Code, source'

 lstrip() example

code

code = '    Code, source    '
code.strip()
print(f'After Removing Leading Whitespaces String =\'{code.lstrip()}\'')

output

After Removing Leading Whitespaces String ='Code, source    '

rstrip() example

code

code = '    Code, source    '
code.strip()
print(f'After Removing Trailing Whitespaces String =\'{code.rstrip()}\'')

output

After Removing Trailing Whitespaces String ='    Code, source'

Share on social media

//