例如,有一个字符串。的例子。
我怎样才能去掉中间的字符,即M ?我不需要密码。我想知道:
Python中的字符串是否以特殊字符结尾? 哪个是更好的方法-从中间字符开始将所有内容从右向左移动或创建一个新字符串而不复制中间字符?
例如,有一个字符串。的例子。
我怎样才能去掉中间的字符,即M ?我不需要密码。我想知道:
Python中的字符串是否以特殊字符结尾? 哪个是更好的方法-从中间字符开始将所有内容从右向左移动或创建一个新字符串而不复制中间字符?
当前回答
删除一个字符或子字符串一次(只删除第一次):
main_string = main_string.replace(sub_str, replace_with, 1)
注意:这里的1可以用任何int替换,表示要替换的出现次数。
其他回答
使用translate()方法:
>>> s = 'EXAMPLE'
>>> s.translate(None, 'M')
'EXAPLE'
取代:取代特定的位置:
s = s[:pos] + s[(pos+1):]
替换一个特定的字符:
s = s.replace('M','')
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
我在这里某处见过。
字符串是不可变的。但是你可以把它们转换成一个可变的列表,然后在你改变它之后再把它转换回字符串。
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
您还可以创建一个新字符串,就像其他人演示的那样,从现有字符串中取出所需字符以外的所有内容。
删除一个字符或子字符串一次(只删除第一次):
main_string = main_string.replace(sub_str, replace_with, 1)
注意:这里的1可以用任何int替换,表示要替换的出现次数。