python - 字符串操作,python

标签 python string

好吧,我需要把大写字母改成小写字母,把小写字母改成大写字母,没关系,但我还需要删除句子中的第一个“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.splitstr.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/

相关文章:

python - 在 Python 中使用索引删除项目的就地函数

python manage.py runserver 抛出错误

python - 使用 dropbox API 下载指定文件夹中的所有图像,而不是子文件夹

java - 字符串数组的数组工作不正确

PHP preg_replace_callback,仅替换 1 个反向引用?

python - 距离树的根搜索失败

python - Tkinter 标签图像无边框

java - 如何将包含路径参数的字符串格式的网址

swift - 循环遍历源代码中的多个实例?

java - Java中字符串初始化