[英]Elegant solutions to replacing multiple characters in a string
I'm scraping a Html report for people using licenses for a bespoke software, as a way to bulk email them asking to free up a license in times of need. 我正在为使用定制软件许可证的人抓取一份HTML报告,作为向他们发送电子邮件的一种方式,以便他们在需要时释放许可证。
I split the string read from the html file into a list, separated by newlines, and .split()
out everything else I don't need (like html formatting, pc name etc.) 我将从html文件中读取的字符串拆分为一个列表,以换行符分隔,然后.split()
删除我不需要的其他所有内容(例如html格式,pc名称等)。
The output from the file however looks like: 但是,文件的输出如下所示:
["foo.bar", 'test.name', "john.doe"] etc.
I added @[companyname].com
to the end of each name, and converted the entire list to a string. 我在每个名称的末尾添加了@[companyname].com
,并将整个列表转换为字符串。 Then, I come to my issue. 然后,我来谈我的问题。 I want to get rid of the unneeded text from the list. 我想摆脱列表中不需要的文本。 as shown below: 如下所示:
onlineUsers = str(userEmailAddress).replace(",",";").replace("[","").replace("]","").replace("'","")
I added the following browser popup with a mailto link at the bottom: 我在底部添加了一个mailto链接,添加了以下浏览器弹出窗口:
webbrowser.open_new("mailto:" + onlineUsers)
And everything works like a dream, however the chaining of .replace()
really bugs me. 一切都像梦一样,但是.replace()
的链接确实让我.replace()
。 I've looked around for more elegant solutions, but they end up being more clunky and it seems like using a sledgehammer on a nail. 我到处寻找更优雅的解决方案,但它们最终变得笨拙,似乎在钉子上使用了大锤。
Is there an elegant way to do multiple replaces simultaneously? 是否有一种优雅的方式可以同时进行多个替换? Or, at least, is there a better way to format this? 或者,至少,有一种更好的格式化方法吗?
To avoid chaining explicitly, you can create a dict()
of text to be replaced as keys and text to be replaced with as values t, something like this : 为了避免显式链接,您可以创建要替换为键的文本的dict()
和要替换为值 t的文本 ,如下所示:
lst = ["blah[,].com", "gen@,]'com"]
rpl = {
"," : ";",
"[" : "",
"]" : "",
"'" : ""
}
lst1 = []
for lst_v in lst :
for k, v in rpl.items():
lst_v = lst_v.replace(k, v)
lst1.append(lst_v)
print lst1
This will result in : 这将导致:
['blah;.com', 'gen@;com']
Please, also read my comment on the original question. 请也请阅读我对原始问题的评论。
As to still provide an answer, something I've used before is this: 为了仍然提供答案,我之前使用过的东西是:
for char in ['b\'', "\'", "\\n", '"', '[', ']', ',']: # Add any kind of char you would like to remove
if char in targeted_variable_value:
clean_output = targeted_variable_value.replace(char, "")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.