例如,有一个字符串。的例子。
我怎样才能去掉中间的字符,即M ?我不需要密码。我想知道:
Python中的字符串是否以特殊字符结尾? 哪个是更好的方法-从中间字符开始将所有内容从右向左移动或创建一个新字符串而不复制中间字符?
例如,有一个字符串。的例子。
我怎样才能去掉中间的字符,即M ?我不需要密码。我想知道:
Python中的字符串是否以特殊字符结尾? 哪个是更好的方法-从中间字符开始将所有内容从右向左移动或创建一个新字符串而不复制中间字符?
当前回答
您可以简单地使用列表推导式。
假设你有字符串:my name is,你想删除字符m.使用以下代码:
"".join([x for x in "my name is" if x is not 'm'])
其他回答
from random import randint
def shuffle_word(word):
newWord=""
for i in range(0,len(word)):
pos=randint(0,len(word)-1)
newWord += word[pos]
word = word[:pos]+word[pos+1:]
return newWord
word = "Sarajevo"
print(shuffle_word(word))
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
我在这里某处见过。
下面是我切掉“M”的方法:
s = 'EXAMPLE'
s1 = s[:s.index('M')] + s[s.index('M')+1:]
我怎样才能去掉中间的字符,即M ?
你不能,因为Python中的字符串是不可变的。
Python中的字符串是否以特殊字符结尾?
不。它们类似于字符列表;列表的长度定义了字符串的长度,没有字符作为结束符。
哪个是更好的方法-从中间字符开始将所有内容从右向左移动或创建一个新字符串而不复制中间字符?
您不能修改现有的字符串,因此必须创建一个包含除中间字符以外的所有内容的新字符串。
字符串在Python中是不可变的,所以这两个选项的意思基本上是一样的。