Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python string replace is deleting whitespace incorrectly

I have a method

def strip_searchname(self, original_name):
    taboo = {" and ", " of ", " at ", " in ", ":", "-", ",", " the ", " "}
    searchname = original_name
    for word in taboo:
        print(searchname)
        searchname = searchname.replace(word, "")
    searchname = re.sub('[^a-zA-Z]', "", searchname)
    searchname= searchname.upper()
    return searchname

(yes, I know parts of it are redundant)

The first .replace seems to be stripping the entire string of whitespace, which I do NOT want. Why is this? How do I avoid it?

(e.g. output is:

Seattle University
SeattleUniversity
SeattleUniversity
SeattleUniversity
SeattleUniversity
SeattleUniversity
SeattleUniversity
SeattleUniversity
SeattleUniversity
SEATTLEUNIVERSITY

)

like image 246
Colleen Avatar asked Jul 23 '26 17:07

Colleen


1 Answers

What I DON'T understand is why it seems to be executing the " " replace BEFORE the " of " replace, for example, when the " of " replace comes before the space in the list.

It's not a list.

taboo = {" and ", " of ", " at ", " in ", ":", "-", ",", " the ", " "}

is a set literal. Try replacing { and } by [ and ] to get the order you want.

like image 83
DSM Avatar answered Jul 26 '26 07:07

DSM



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!