Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Remove Trailing Whitespace From A Python String With .rstrip()

Call `.rstrip()`` on a python string to remove any trailing whitespace (including newline characters). For example, this text has both leading and trailing whitespace and newlines. Calling `.rstrip()`` trims the trailing characters while leaving the leading characters in place. For example, this removes the trailing spaces and newlines from the the string while leaving the leading characters alone

Code

original = """

    echo foxtrot golf   

    """

right_stripped = original.rstrip()

print(f"START|{right_stripped}|END")

Results

START|

    echo foxtrot golf|END