例如,有一个字符串。的例子。

我怎样才能去掉中间的字符,即M ?我不需要密码。我想知道:

Python中的字符串是否以特殊字符结尾? 哪个是更好的方法-从中间字符开始将所有内容从右向左移动或创建一个新字符串而不复制中间字符?


当前回答

Python 3.9+中引入了两个新的字符串删除方法

#str.removeprefix("prefix_to_be_removed")
#str.removesuffix("suffix_to_be_removed")

s='EXAMPLE'

在这个例子中,M的位置是3

s = s[:3] + s[3:].removeprefix('M')

OR

s = s[:4].removesuffix('M') + s[4:]

#output'EXAPLE'

其他回答

在Python 2中,可以使用UserString。MutableString以可变的方式来做:

>>> import UserString
>>> s = UserString.MutableString("EXAMPLE")
>>> type(s)
<class 'UserString.MutableString'>
>>> del s[3]    # Delete 'M'
>>> s = str(s)  # Turn it into an immutable value
>>> s
'EXAPLE'

MutableString在Python 3中被移除。

使用translate()方法:

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

您可以简单地使用列表推导式。

假设你有字符串:my name is,你想删除字符m.使用以下代码:

"".join([x for x in "my name is" if x is not 'm'])
card = random.choice(cards)
cardsLeft = cards.replace(card, '', 1)

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

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

我在这里某处见过。