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

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

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


当前回答

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

我在这里某处见过。

其他回答

这可能是最好的方法:

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

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

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

我在这里某处见过。

另一种方法是用一个函数,

下面是通过调用函数从字符串中删除所有元音的方法

def disemvowel(s):
    return s.translate(None, "aeiouAEIOU")

在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中被移除。

取代:取代特定的位置:

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

替换一个特定的字符:

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