Marius Marius - 6 months ago 8
Python Question

Remove first and last specific symbol

How I can remove first and last " i " from input text? 1st variant removes text last letter and duplicates:

Entered TexEntered Text
^ ^


2nd variant does nothing.

Code:

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)

Answer

You can use a regular expression:

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)

Another, shorter way of doing the same.

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