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.
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.)
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. 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:
webbrowser.open_new("mailto:" + onlineUsers)
And everything works like a dream, however the chaining of .replace()
really bugs me. 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 :
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, "")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.