好吧,我需要把大写字母改成小写字母,把小写字母改成大写字母,没关系,但我还需要删除句子中的第一个“i”字母和最后一个“i”字母。有任何想法吗?另外,如果输入文本中没有“i”字母,我该如何打印文本? 谢谢。
这是我目前所得到的:
print("Write a sentence.")
sentence = input()
first = sentence.find("i")
second = sentence.rfind("i")
sentence.replace(first, " ")
sentence.replace(second, " ")
print(sentence.swapcase())
最佳答案
使用 str.replace
使用 count
参数,您只能删除 n 次出现的子字符串。
>>> sentence = 'Hello, This is string.'
>>> sentence = sentence.replace('i', '', 1) # Replace the first occurence of `i`
>>> sentence = sentence[::-1].replace('i', '', 1)[::-1] # reverse/replace/reverse
>>> sentence.swapcase()
'hELLO, tHS IS STRNG.'
注意:str.replace
区分大小写。上面的代码只删除了小写的i
。
替代使用 str.join
, str.split
和 str.rsplit
. str.*split
接受可选的 maxsplit
参数,类似于 str.replace
:
>>> sentence = 'Hello, This is string.'
>>> sentence = ''.join(sentence.split('i', 1))
>>> sentence = ''.join(sentence.rsplit('i', 1))
>>> sentence.swapcase()
'hELLO, tHS IS STRNG.'
关于python - 字符串操作,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21377031/