gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:09:55 26 4
gpt4 key购买 nike

如何从输入文本中删除第一个和最后一个“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)

最佳答案

您可以使用正则表达式:

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)

关于python - 删除第一个和最后一个特定符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35105189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com