-1

I understand that str = str.replace('x', '') will eliminate all the x's.

But let's say I have a string jxjrxxtzxz and I only want to delete the first and last x making the string jjrxxtzz. This is not string specific. I want to be able to handle all strings, and not just that specific example.

edit: assume that x is the only letter I want to remove. Thank you!

4

2 回答 2

0

One fairly straight forward way is to just use find and rfind to locate the characters to remove;

s = 'jxjrxxtzxz'

# Remove first occurrence of 'x'
ix = s.find('x')
if ix > -1:
   s = s[:ix]+s[ix+1:]

# Remove last occurrence of 'x'
ix = s.rfind('x')
if ix > -1:
   s = s[:ix]+s[ix+1:]
于 2013-10-22T04:50:08.413 回答
0

Not pretty but this will work:

def remove_first_last(c, s):
    return s.replace(c,'', 1)[::-1].replace(c,'',1)[::-1]

Usage:

In [1]: remove_first_last('x', 'jxjrxxtzxz')
Out[1]: 'jjrxxtzz'
于 2013-10-22T05:00:40.930 回答