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
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
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))
在Python中,字符串是不可变的,所以你必须创建一个新的字符串。 对于如何创建新的字符串,你有几个选择。 如果你想在出现'M'的地方去掉它。
如果你想删除中心字符。
你问的是字符串是否以特殊字符结尾。 不,你的想法和C程序员一样。 在Python中,字符串是以其长度来存储的,所以任何字节值,包括
0
,都可以出现在一个字符串中。这可能是最好的方法。
不要担心字符转换之类的问题。大多数Python代码发生在一个更高的抽象层次上。
替换一个特定的职位。
替换一个特定的字符。
字符串是不可变的。 但是你可以将它们转换为一个列表,而列表是可以改变的,然后在你改变了列表之后再将其转换回字符串。
你也可以创建一个新的字符串,就像其他人所展示的那样,从现有的字符串中提取除了你想要的字符之外的所有内容。
你不能,因为Python中的字符串是[不可变的][1]。
没有。 它们类似于字符列表。 列表的长度定义了字符串的长度,没有字符作为结束符。
你不能修改现有的字符串,所以你必须创建一个新的字符串,包含除中间字符以外的所有内容。
[1]: http://en.wikipedia.org/wiki/Immutable_object
使用 [
translate()
][1] 方法。[1]: http://docs.python.org/2/library/string.html#string.translate
[UserString.MutableString][1]
可互换的方式。
[1]: http://docs.python.org/library/userdict.html#UserString.MutableString
我曾在某处看到过这里。
如何从字符串中删除一个字符:。 下面是一个例子,在一个字符串中,有一叠牌作为字符表示。 其中一张牌被抽出(导入随机模块的random.choice()函数,在字符串中随机抽取一个字符)。 一个新的字符串cardLeft被创建,用来存放字符串函数replace()给出的剩余卡片,其中最后一个参数表示只有一个"card" 要被空字符串替换... ...
下面'就是我为了切出"M"所做的。
如果你想删除/忽略一个字符串中的字符,例如,你有这个字符串。
"[11:L:0]"。
从一个Web API响应或类似的东西,像一个CSV文件,让我们'say you are using requests
循环,去掉不需要的字符。
可选拆分,你将可以单独读取数值。
现在,访问每个值更容易了。
这将打印
删除一个 "char "或 "sub-string "一次(只有第一次出现)。
注:这里的 "1 "可以用任何一个 "int "来代替你想要替换的出现次数。 这里的
1
可以用任何int
代替你要替换的出现次数。你可以简单地使用列表理解。
假设你有一个字符串:"我的名字是",你想删除字符 "m"。 "我的名字是",你想删除字符 "m"。 使用以下代码。
在Python中,字符串是不可变的,所以你的两个选项的意思基本上是一样的。