Remove last character if it's a backslash
Is there a function to chomp last character in the string if it's some special character? For example, I need to remove backslash if it's there, and do nothing, if not. I know I can do it with regex easily, but wonder if there something like a small built-in function for that.
Solution 1:
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
Solution 2:
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]
Solution 3:
If you only want to remove one backslash in the case of multiple, do something like:
s = s[:-1] if s.endswith('\\') else s
Solution 4:
if s.endswith('\\'):
s = s[:-1]