简体   繁体   中英

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.

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

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('\\');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM