In a web scraping I'm stuck in replace() function. I want to replace any spaces with dash in a string but it's not working in this sentence, but works in others. I don't know what's wrong with this sentence:
description = "Cooler Master MasterLiquid Lite 240" # got this from html
#description = "hello world"
replace = description.replace('\s+', '-').replace(' ', '-')
print(replace)
#output: Cooler-Master- MasterLiquid-Lite-240
Working Snippet
The split/join technique proposed by @Rodalm is excellent. However, for the sake of completeness, here's the re approach:
import re
description = "Cooler Master MasterLiquid Lite 240"
print(re.sub('\s+', '-', description))
Output:
Cooler-Master-MasterLiquid-Lite-240
str.replace doesn't support the use of regular expressions. If you want to search and replace regular expressions you have to import the built-in re module and use re.sub (or something similar).
But I think using regular expression here is overkill. You can just use str.split + str.join
description = "Cooler Master MasterLiquid Lite 240"
replace = '-'.join(description.split())
print(replace)
Output:
Cooler-Master-MasterLiquid-Lite-240
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With