[英]Python: Delete a character from a string
I want to delete ie character number 5 in a string. 我想删除字符串中的字符编号5。 So I did: 所以我做了:
del line[5] 德尔线[5]
and got: TypeError: 'str' object doesn't support item deletion 并得到:TypeError:'str'对象不支持删除项目
So no I wonder whether there is a different efficient solution to the problem. 所以,我不知道是否有一个不同的有效解决方案。
Strings are immutable in Python, so you can't change them in-place. 字符串在Python中是不可变的,因此您无法就地更改它们。
But of course you can assign a combination of string slices back to the same identifier: 但是,您当然可以将字符串切片的组合分配回相同的标识符:
mystr = mystr[:5] + mystr[6:]
I use a function similar to : 我使用类似的功能:
def delstring(mystring, indexes):
return ''.join([let for ind, let in enumerate(mystring) if ind not in indexes])
indexes should be an iterable (list, tuple..) 索引应该是可迭代的(list,tuple ..)
bytearray is a type which can be changed in place. bytearray是一种可以在适当位置更改的类型。 And if you are using Python2.x, it can very easily convert to default str type: bytes. 如果您使用的是Python2.x,它可以很容易地转换为默认的str类型:bytes。
b=bytearray(s)
del b[5]
s=str(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.