Python has three inbuilt function to trim string- strip(), lstrip(), rstrip(). These functions in python are used to trim whitespaces, tabs (\t) and newline (\n) from the string.

Let’s see how to trim string in python with examples but first understand each of the three methods.

Python strip(), lstrip(), rstrip()

  • strip() – This function returns a new modified string after triming leading and trailing whitespace (whitespaces on left and right), tabs (\t) and newline (\n).
  • lstrip() – This function returns a new modified string after removing the whitespaces, tabs (\t) and newline (\n) from the left (leading) side of the string.
  • rstrip() – This function returns a new modified string after removing the whitespaces, tabs (\t) and newline (\n) from the right (traling) side of the string.

Let’s see dome examples of Python trim.

Example 1: strip()

Output

Python strip() Example

Example 2: lstrip()

Output

Python lstrip() Example

Example 3: rstrip()

Output

Python rstrip() Example

rstrip() only trimmed the right newline character (\n) of \n \t Remove Whitespaces \n, left part remains unaffected.

If you have any doubts then comment below.

Leave a Reply

Close Menu