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

时间:2016-01-30 18:05:41

标签: python

如何从输入文本中删除第一个和最后一个“i”?第一个变体删除文本的最后一个字母和重复:

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 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

正如评论中所提到的,您尝试对列表使用or==,而这些列表只是在Python中不起作用。

您需要分别检查每个角色。

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!")

而不是"I" or "i"(它总是返回"I",因为它是第一个True值),我们为每个find()rfind()执行(从一组),然后找到不是-1的最小值和找到最左边和最右边的出现的最大值,然后我们可以像以前一样进行替换。