如何使用 Python 从字符串中删除字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3559559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:43:37  来源:igfitidea点击:

How to delete a character from a string using Python

pythonstring

提问by Lazer

There is a string, for example. EXAMPLE.

例如,有一个字符串。EXAMPLE.

How can I remove the middle character, i.e., Mfrom it? I don't need the code. I want to know:

如何删除中间字符,即M从中删除?我不需要代码。我想知道:

  • Do strings in Python end in any special character?
  • Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string and not copying the middle character?
  • Python 中的字符串是否以任何特殊字符结尾?
  • 哪个是更好的方法 - 从中​​间字符开始从右向左移动所有内容或创建新字符串而不复制中间字符?

采纳答案by Ned Batchelder

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:

在 Python 中,字符串是不可变的,因此您必须创建一个新字符串。您有几个关于如何创建新字符串的选项。如果您想删除出现在任何地方的“M”:

newstr = oldstr.replace("M", "")

If you want to remove the central character:

如果要删除中心字符:

midlen = len(oldstr)/2   # //2 in python 3
newstr = oldstr[:midlen] + oldstr[midlen+1:]

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.

您询问字符串是否以特殊字符结尾。不,您像 C 程序员一样思考。在 Python 中,字符串与其长度一起存储,因此任何字节值,包括\0,都可以出现在字符串中。

回答by recursive

This is probably the best way:

这可能是最好的方法:

original = "EXAMPLE"
removed = original.replace("M", "")

Don't worry about shifting characters and such. Most Python code takes place on a much higher level of abstraction.

不要担心转换字符等。大多数 Python 代码发生在更高的抽象级别上。

回答by Eton B.

To replace a specific position:

要替换特定位置:

s = s[:pos] + s[(pos+1):]

To replace a specific character:

要替换特定字符:

s = s.replace('M','')

回答by Skilldrick

Strings are immutable in Python so both your options mean the same thing basically.

字符串在 Python 中是不可变的,因此您的两个选项基本上意味着相同的事情。

回答by Richard Fearn

How can I remove the middle character, i.e., M from it?

如何从中删除中间字符,即 M ?

You can't, because strings in Python are immutable.

你不能,因为 Python 中的字符串是不可变的

Do strings in Python end in any special character?

Python 中的字符串是否以任何特殊字符结尾?

No. They are similar to lists of characters; the length of the list defines the length of the string, and no character acts as a terminator.

不。它们类似于字符列表;列表的长度定义了字符串的长度,没有字符充当终止符。

Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string and not copying the middle character?

哪个是更好的方法 - 从中​​间字符开始从右向左移动所有内容或创建新字符串而不复制中间字符?

You cannot modify the existing string, so you must create a new one containing everything except the middle character.

您无法修改现有字符串,因此您必须创建一个包含除中间字符以外的所有内容的新字符串。

回答by killown

UserString.MutableString

用户字符串.可变字符串

Mutable way:

可变方式:

import UserString

s = UserString.MutableString("EXAMPLE")

>>> type(s)
<type 'str'>

# Delete 'M'
del s[3]

# Turn it for immutable:
s = str(s)

回答by kindall

Strings are immutable. But you can convert them to a list, which is mutable, and then convert the list back to a string after you've changed it.

字符串是不可变的。但是您可以将它们转换为可变的列表,然后在更改列表后将其转换回字符串。

s = "this is a string"

l = list(s)  # convert to list

l[1] = ""    # "delete" letter h (the item actually still exists but is empty)
l[1:2] = []  # really delete letter h (the item is actually removed from the list)
del(l[1])    # another way to delete it

p = l.index("a")  # find position of the letter "a"
del(l[p])         # delete it

s = "".join(l)  # convert back to string

You can also create a new string, as others have shown, by taking everything exceptthe character you want from the existing string.

您还可以创建一个新字符串,正如其他人所展示的那样,通过从现有字符串中获取您想要的字符之外的所有内容。

回答by user1443297

def kill_char(string, n): # n = position of which character you want to remove
    begin = string[:n]    # from beginning to n (n not included)
    end = string[n+1:]    # n+1 through end of string
    return begin + end
print kill_char("EXAMPLE", 3)  # "M" removed

I have seen this somewhere here.

我看到这个地方在这里

回答by StaffanRolfsson

card = random.choice(cards)
cardsLeft = cards.replace(card, '', 1)

How to remove one character from a string:Here is an example where there is a stack of cards represented as characters in a string. One of them is drawn (import random module for the random.choice() function, that picks a random character in the string). A new string, cardsLeft, is created to hold the remaining cards given by the string function replace() where the last parameter indicates that only one "card" is to be replaced by the empty string...

如何从字符串中删除一个字符:这是一个示例,其中有一叠卡片表示为字符串中的字符。其中之一被绘制(为 random.choice() 函数导入 random 模块,在字符串中选择一个随机字符)。一个新的字符串,cardsLeft,被创建来保存由字符串函数 replace() 给出的剩余卡片,其中最后一个参数表示只有一张“卡片”将被空字符串替换......

回答by Stefan van den Akker

Use the translate()method:

使用translate()方法:

>>> s = 'EXAMPLE'
>>> s.translate(None, 'M')
'EXAPLE'