### 删除第一个和最后一个特定符号

``````Entered TexEntered Text
^           ^
``````

``````txt4 = input("Enter text: ")
txt4 = txt4.swapcase()
print(txt4)
x = "I" or "i"
x1 = txt4.find(x)
x2 = txt4.rfind(x)
if [x1, x2] == -1:
print("Letter \"i\" not found!")
else:
#txt4 = txt4.replace(txt4[0:(x1+1)], "", 1) #]
#txt4 = txt4.replace(txt4[(x2):0], "", 1)   #]-2nd variant
#txt4x1 = txt4[:(x1+1)] + txt4[(x2):]       #]
txt4x1 = txt4[0:x1]+txt4[(x1+1):]
txt4x1 = txt4[0:x2]+txt4[(x2+1):]
print(txt4x1)
``````

#### 2 个答案:

``````import re
regex = re.compile('i', flags=re.IGNORECASE)
txt = input("Enter text: ")
# re.sub() always searches from left, so we reverse txt using slice [::-1]
# to find the last match. Then we flip it again.
txt = regex.sub('', txt[::-1], 1)
txt = regex.sub('', txt[::-1], 1)
print(txt)
``````

``````txt = input("Enter text: ")
for direction in 'from right', 'from left':  # do it twice
txt = re.sub('[iI]', '', txt[::-1], count=1)
print(txt)
``````

``````swappedCase = input("Enter text: ").swapcase()
print(swappedCase)
letters = {"I", "i"}
leftPositions = {swappedCase.find(letter) for letter in letters}
leftPos = min((position for position in leftPositions if position > -1), default=-1)
rightPos = max(swappedCase.rfind(letter) for letter in letters)
if leftPos > -1 or rightPos > -1:
altered = swappedCase
if leftPos > -1:
altered = altered[:leftPos]+txt4[leftPos+1:]
if rightPos > -1:
altered = altered[:rightPos]+txt4[rightPos+1:]
print(altered)
else:
print("Letter \"i\" not found!")
``````