Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python replace spaces not affacted

Tags:

python

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

like image 914
tour travel Avatar asked Apr 28 '26 12:04

tour travel


2 Answers

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
like image 118
Ramrab Avatar answered Apr 30 '26 01:04

Ramrab


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
like image 39
Rodalm Avatar answered Apr 30 '26 00:04

Rodalm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!