Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字符串中删除多个子字符串_Python_String - Fatal编程技术网

Python 从字符串中删除多个子字符串

Python 从字符串中删除多个子字符串,python,string,Python,String,我想在一个字符串中替换多个子字符串,我想知道哪种方法最有效/最佳实践 我试过使用str.replace,它可以工作,但效率似乎很低。我正在运行Python3.6,所以我想要一个与之兼容的解决方案 对于这里的一些上下文,我想从我读到的一些文本中创建一个新类的名称。因此,我需要将文本转换为有效Python标识符的字符串,例如,坏类名变为坏类名。因此,虽然我提出的在单个字符串中替换多个子字符串的最佳方法仍然有效,但如果有更好的方法将文本转换为类名,我也很乐意听到这一点 我现时的守则如下: my_str

我想在一个字符串中替换多个子字符串,我想知道哪种方法最有效/最佳实践

我试过使用str.replace,它可以工作,但效率似乎很低。我正在运行Python3.6,所以我想要一个与之兼容的解决方案

对于这里的一些上下文,我想从我读到的一些文本中创建一个新类的名称。因此,我需要将文本转换为有效Python标识符的字符串,例如,坏类名变为坏类名。因此,虽然我提出的在单个字符串中替换多个子字符串的最佳方法仍然有效,但如果有更好的方法将文本转换为类名,我也很乐意听到这一点

我现时的守则如下:

my_str=my_str.replace、.replace、.replace/、.replace'、.replace-、.replace',
有更好的方法吗?正则表达式、for循环、一些我不知道的内置字符串方法?

用regexp替换:

import re

my_str = "bad-Classname's"
my_str = re.sub(r"[ ,/'’-]", "", my_str)
print(my_str)   # badClassnames
[,/“”-]-regex字符类,匹配列表中的单个字符,/“”-
使用regexp替换:

import re

my_str = "bad-Classname's"
my_str = re.sub(r"[ ,/'’-]", "", my_str)
print(my_str)   # badClassnames
[,/“”-]-regex字符类,匹配列表中的单个字符,/“”-
您可以使用以下内容:

string = 'this is a test string'
items_to_remove = ['this', 'is', 'a', 'string']

In [1]: [x for x in string.split() if x not in {'is', 'this', 'a', 'string'}]
Out[1]: ['test']

希望这能回答您的问题。

您可以使用以下内容:

string = 'this is a test string'
items_to_remove = ['this', 'is', 'a', 'string']

In [1]: [x for x in string.split() if x not in {'is', 'this', 'a', 'string'}]
Out[1]: ['test']
希望这能回答您的问题。

使用str.translate 使用str.translate