Python Tutorials

How to remove trailing newline in Python - rstrip() method

Syntax:

str.rstrip('characters')

'characters' is optional


Remove trailing newline character :

str = 'Hey there\n'
new_str = str.rstrip('\n')
print(new_str)

Output:

>>>Hey there


  • If you just want to remove spaces in the end, then :
  • str = 'Hey there    '
    new_str = str.rstrip()
    print(new_str)


    Output:

    >>>Hey there


  • Just like strip() method the order and number of the characters passed in the rstrip() method does not matter.
  • str = 'heeyyyyyy'
    new_str = str.rstrip('ye')
    print(new_str)


    Output:

    >>>h


    Also read: strip() method and lstrip() method