Jack The Baker
Jack The Baker

Reputation: 1883

python replace spaces not affacted

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

Upvotes: 2

Views: 73

Answers (4)

Adon Bilivit
Adon Bilivit

Reputation: 26925

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

Upvotes: 3

Pamira
Pamira

Reputation: 129

The following will work as mentioned by @Rodalm

import re
description = "Cooler Master    MasterLiquid Lite 240"
#description = "hello world"
replace = re.sub('\s+', '-',description)
print(replace)

Upvotes: 2

Rodalm
Rodalm

Reputation: 5433

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

Upvotes: 3

Cardstdani
Cardstdani

Reputation: 5223

You can use split() and join() to erase unnecessary spaces, and then replace single space characters with - sign or whatever string you need:

description = "Cooler Master    MasterLiquid Lite 240"
replace = ' '.join(description.split()).replace(' ', '-')
#replace = '-'.join(description.split()) #More efficient alternative, avoiding replace()
print(replace)

Output:

Cooler-Master-MasterLiquid-Lite-240

Upvotes: 2

Related Questions