如何使用 Python 从字符串中删除字符 [英] How to delete a character from a string using 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 中,字符串是与其长度一起存储,因此任何字节值,包括 \0
,可以出现在字符串中.
You asked if strings end with a special character. No, you are thinking like a C programmer. In Python, strings are stored with their length, so any byte value, including \0
, can appear in a string.
这篇关于如何使用 Python 从字符串中删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!