Remove last character if it's a backslash

Use rstrip to strip the specified character(s) from the right side of the string.

my_string = my_string.rstrip('\\')

See: http://docs.python.org/library/stdtypes.html#str.rstrip


If you don't mind all trailing backslashes being removed, you can use string.rstrip()

For example:

x = '\\abc\\'
print x.rstrip('\\')

prints:

\abc

But there is a slight problem with this (based on how your question is worded): This will strip ALL trailing backslashes. If you really only want the LAST character to be stripped, you can do something like this:

if x[-1] == '\\': x = x[:-1]

If you only want to remove one backslash in the case of multiple, do something like:

s = s[:-1] if s.endswith('\\') else s

Tags:

Python

String