Python 从字符串中删除字符
我需要一个从字符串中删除字符的函数Python 从字符串中删除字符,python,string,Python,String,我需要一个从字符串中删除字符的函数remove() 这是我的第一个方法: def remove(self, string, index): return string[0:index] + string[index + 1:] def remove_indexes(self, string, indexes): for index in indexes: string = self.remove(string, index) return string
remove()
这是我的第一个方法:
def remove(self, string, index):
return string[0:index] + string[index + 1:]
def remove_indexes(self, string, indexes):
for index in indexes:
string = self.remove(string, index)
return string
在数组中传递要删除的索引,但一旦删除字符,整个索引就会改变
还有比这更像蟒蛇的猛击吗。这样实施会更容易:
"hello".remove([1, 2])
我不知道“蟒蛇式”的方法,但你可以做到这一点。如果您可以确保在remove_index
中始终对索引进行排序,则可以执行此操作
def remove_indexes(self, string, indexes):
for index in indexes.reverse():
string = self.remove(string, index)
return string
如果你不能保证,那就去做吧
def remove_indexes(self, string, indexes):
for index in indexes.sort(reverse=True):
string = self.remove(string, index)
return string
最具python风格的方式是使用。索引方法的危险在于,您传递的字符串可能具有可变长度,因此您可能会无意中删除部分字符串 假设您想删除字符串中的所有数字
import re
s = "This is a string with s0m3 numb3rs in it1 !"
num_reg = re.compile(r"\d+") # catches all digits 0-9
re.sub(num_reg , "**", s) # substitute numbers in `s` with "**"
>>> "This is a string with s**m** numb**rs in it** !"
通过这种方式,您可以定义一个常规表达式,该表达式可能定期出现在字符串中(“正则表达式”或正则表达式),并且可以快速可靠地替换字符串中该正则表达式的所有实例。您不能将属性添加到内置的
类型中,您将遇到如下错误:
TypeError: can't set attributes of built-in/extension type 'str'
您可以创建继承str
的类,并添加此方法:
class String(str):
def remove(self, index):
if isinstance(index, list):
# order the index to remove the biggest first
for i in sorted(index, reverse=True):
self = self.remove(i)
return self
return String(self[0:index] + self[index + 1:])
s = String("hello")
print(s.remove([0, 1]))
如果要进行适当的更改,则需要创建新类型,例如:
class String:
def __init__(self, value):
self._str = value
def __getattr__(self, item):
""" delegate to str"""
return getattr(self._str, item)
def __getitem__(self, item):
""" support slicing"""
return String(self._str[item])
def remove(self, indexex):
indexes = indexex if isinstance(indexex, list) else [indexex]
# order the index to remove the biggest first
for i in sorted(indexes, reverse=True):
self._str = self._str[0:i] + self._str[i + 1:]
# change in place should return None
return None
def __str__(self):
return str(self._str)
def __repr__(self):
return repr(self._str)
s = String("hello")
s.remove([0, 1])
print(s.upper()) # delegate to str class
print(s[:1]) # support slicing
print(list(x for x in s)) # it's iterable
但是仍然缺少另一个像真正的str
类一样工作的神奇方法。像\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
如果您想要像str
这样的类,但有一个remove
方法来更改实例本身,则需要创建自己的可变类型,str
是基本不可变类型和self=self.remove(i)
不会真正更改变量,因为它只是将self
参数的引用更改为另一个对象
,但是引用s
仍然指向由字符串(“hello”)
创建的同一个对象。我认为下面的代码对您适用。它删除了索引(要从字符串中删除的)并返回由剩余索引组成的连接字符串
def remove_indexes(string,indexes):
return "".join([string[i] for i in range(len(string)) if i not in indexes])
remove_indexes("hello",[1,2])
i=String(“hello”)i.remove([0,1])打印(i)
不工作。因为self=self.remove(i)
没有编辑变量。对于额外的代码,很抱歉,问题是您无法将属性添加到内置str
类型,因此无法添加任何方法。是的,我应该返回字符串类型。很抱歉,str
是基本类型,您无法在适当的位置更改它们。希望这对您有所帮助,问题是str是不可变的,您需要o创建一个行为类似str的新类。您可以查看我的编辑,但可能有比这个更好的解决方案,我现在真的不知道