繁体   English   中英

从字符串 Python 中删除多个 substring

[英]Remove multiple substring from a string Python

我想替换单个字符串中的多个子字符串,并且我想知道哪种方法最有效/最佳实践。

我试过使用 str.replace() 并且它有效,但这似乎效率低下。 我正在运行 Python 3.6,所以我想要一个与之兼容的解决方案。

对于这里的一些上下文,我想从我阅读的一些文本中创建一个(新的)class 的名称。 所以我需要将文本转换为(字符串)有效的 Python 标识符(例如,“bad-Classname's”变成“badClassnames”)。 因此,虽然我关于在单个字符串中替换多个子字符串的最佳方法的问题仍然存在,但如果有更好的方法将文本转换为 class 名称,我也会很高兴听到这一点。

我现有的代码如下:

my_str = my_str.replace(" ", "").replace(",", "").replace("/", "").replace("'", "").replace("-", "").replace("’", "")

有一个更好的方法吗? 正则表达式、for 循环、一些我不知道的内置字符串方法?

很快用正则表达式替换:

import re

my_str = "bad-Classname's"
my_str = re.sub(r"[ ,/'’-]", "", my_str)
print(my_str)   # badClassnames

  • [,/''-] - 正则表达式字符 class,匹配列表中的单个字符“ ,/''-

使用 str.translate()

# this line builds the translation table
# and can be done once
table = str.maketrans({c:'' for c in " ,/'-’"})

my_str = "bad-Classname's"

# this line does the replacement
my_str = my_str.translate(table)

print(my_str)   
# >>> badClassnames

你可以使用这样的东西:

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']

希望这能回答您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM