Python Trim String Example | rstrip(), lstrip(), strip() Function
Posted on: July 25, 2020 by Deven
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.
- The strip() string method will return a new string without any whitespace characters at the beginning or end.
- The lstrip() method will remove whitespace characters from the left side
- 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
//