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

有一个字符串,例如。EXAMPLE

我怎样才能删除中间的字符,即`M'?我不需要代码。我想知道。

  • Python中的字符串是否以任何特殊字符结束?
  • 哪种方法更好--从中间字符开始从右向左移动所有内容,或者创建一个新的字符串,不复制中间字符?
对该问题的评论 (1)
解决办法

在Python中,字符串是不可变的,所以你必须创建一个新的字符串。 对于如何创建新的字符串,你有几个选择。 如果你想在出现'M'的地方去掉它。

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

如果你想删除中心字符。

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

你问的是字符串是否以特殊字符结尾。 不,你的想法和C程序员一样。 在Python中,字符串是以其长度来存储的,所以任何字节值,包括0,都可以出现在一个字符串中。

评论(3)

这可能是最好的方法。

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

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

评论(3)

替换一个特定的职位。

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

替换一个特定的字符。

s = s.replace('M','')
评论(3)

字符串是不可变的。 但是你可以将它们转换为一个列表,而列表是可以改变的,然后在你改变了列表之后再将其转换回字符串。

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

你也可以创建一个新的字符串,就像其他人所展示的那样,从现有的字符串中提取除了你想要的字符之外的所有内容。

评论(1)

怎样才能去掉中间的字符,即M?

你不能,因为Python中的字符串是[不可变的][1]。

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

没有。 它们类似于字符列表。 列表的长度定义了字符串的长度,没有字符作为结束符。

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

你不能修改现有的字符串,所以你必须创建一个新的字符串,包含除中间字符以外的所有内容。

[1]: http://en.wikipedia.org/wiki/Immutable_object

评论(0)

使用 [translate()][1] 方法。

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

[1]: http://docs.python.org/2/library/string.html#string.translate

评论(3)

[UserString.MutableString][1]

可互换的方式。

import UserString

s = UserString.MutableString("EXAMPLE")

>>> type(s)


# Delete 'M'
del s[3]

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

[1]: http://docs.python.org/library/userdict.html#UserString.MutableString

评论(1)
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

我曾在某处看到过这里

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

如何从字符串中删除一个字符:。 下面是一个例子,在一个字符串中,有一叠牌作为字符表示。 其中一张牌被抽出(导入随机模块的random.choice()函数,在字符串中随机抽取一个字符)。 一个新的字符串cardLeft被创建,用来存放字符串函数replace()给出的剩余卡片,其中最后一个参数表示只有一个"card" 要被空字符串替换... ...

评论(0)

下面'就是我为了切出"M"所做的。

s = 'EXAMPLE'
s1 = s[:s.index('M')] + s[s.index('M')+1:]
评论(1)

如果你想删除/忽略一个字符串中的字符,例如,你有这个字符串。

"[11:L:0]&quot。

从一个Web API响应或类似的东西,像一个CSV文件,让我们'say you are using requests

import requests
udid = 123456
url = 'http://webservices.yourserver.com/action/id-' + udid
s = requests.Session()
s.verify = False
resp = s.get(url, stream=True)
content = resp.content

循环,去掉不需要的字符。

for line in resp.iter_lines():
  line = line.replace("[", "")
  line = line.replace("]", "")
  line = line.replace('"', "")

可选拆分,你将可以单独读取数值。

listofvalues = line.split(':')

现在,访问每个值更容易了。

print listofvalues[0]
print listofvalues[1]
print listofvalues[2]

这将打印

11

L

0

评论(0)

删除一个 "char "或 "sub-string "一次(只有第一次出现)。

main_string = main_string.replace(sub_str, replace_with, 1)

注:这里的 "1 "可以用任何一个 "int "来代替你想要替换的出现次数。 这里的1可以用任何int代替你要替换的出现次数。

评论(0)

你可以简单地使用列表理解。

假设你有一个字符串:"我的名字是",你想删除字符 "m"。 "我的名字是",你想删除字符 "m"。 使用以下代码。

"".join([x for x in "my name is" if x is not 'm'])
评论(0)
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))
评论(1)

在Python中,字符串是不可变的,所以你的两个选项的意思基本上是一样的。

评论(0)