如何使用 Python 从字符串中删除一个字符 [英] How to delete a character from a string using Python
本文介绍了如何使用 Python 从字符串中删除一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,有一个字符串.示例
.
There is a string, for example. EXAMPLE
.
如何从中删除中间字符,即 M
?我不需要代码.我想知道:
How can I remove the middle character, i.e., M
from it? I don't need the code. I want to know:
- Python 中的字符串是否以任何特殊字符结尾?
- 哪个是更好的方法 - 从中间字符开始从右向左移动所有内容或创建新字符串而不复制中间字符?
推荐答案
在 Python 中,字符串是不可变的,因此您必须创建一个新字符串.您有几个创建新字符串的选项.如果您想删除出现在任何地方的M":
In Python, strings are immutable, so you have to create a new string. You have a few options of how to create the new string. If you want to remove the 'M' wherever it appears:
newstr = oldstr.replace("M", "")
如果要删除中心字符:
midlen = len(oldstr) // 2
newstr = oldstr[:midlen] + oldstr[midlen+1:]
您询问字符串是否以特殊字符结尾.不,您像 C 程序员一样思考.在 Python 中,字符串与它们的长度一起存储,因此任何字节值,包括