如果最后一个字符是反斜杠,请删除它

如果字符串中的最后一个字符是某个特殊的字符,是否有一个函数来删除该字符串中的最后一个字符?例如,如果有反斜杠,我需要删除它,如果没有,则什么也不做。我知道我可以很容易地用 regex 做到这一点,但是不知道是否有一个类似于小型内置函数的东西。

90705 次浏览

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]

The rstrip function will remove more than just the last character, though. It will remove all backslashes from the end of the string. Here's a simple if statement that will remove just the last character:

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

Or not so beautiful(don't beat me) but also works:

stripSlash = lambda strVal: strVal[:-1] if strVal.endswith('\\') else strVal
stripSlash('sample string with slash\\')

And yes - rstrip is better. Just want to try.

if s.endswith('\\'):
s = s[:-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

We can use built-in function replace

my_str.replace(my_char,'')

my_chars = '\\'
my_str = my_str.replace(my_char,'')

This will replace all \ in my_str

my_str.replace(my_chars, '',i)

my_char = '\\'
my_str = 'AB\CD\EF\GH\IJ\KL'
print ("Original my_str : "+ my_str)
for i in range(8):
print ("Replace '\\' %s times" %(i))
print("     Result : "+my_str.replace(my_chars, '',i))

This will replace \ in my_str i times Now you can control how many times you want to replace it with i

Output:

Original my_str : AB\CD\EF\GH\IJ\KL
Replace '\' 0 times
Result : AB\CD\EF\GH\IJ\KL
Replace '\' 1 times
Result : ABCD\EF\GH\IJ\KL
Replace '\' 2 times
Result : ABCDEF\GH\IJ\KL
Replace '\' 3 times
Result : ABCDEFGH\IJ\KL
Replace '\' 4 times
Result : ABCDEFGHIJ\KL
Replace '\' 5 times
Result : ABCDEFGHIJKL
Replace '\' 6 times
Result : ABCDEFGHIJKL
Replace '\' 7 times
Result : ABCDEFGHIJKL

For C# people who end up here:

my_string = my_string.TrimEnd('\\');