gpt4 book ai didi

python 字符串替换错误地删除了空格

转载 作者:太空宇宙 更新时间:2023-11-03 12:42:04 26 4
gpt4 key购买 nike

我有一个方法

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

(是的,我知道部分内容是多余的)

第一个 .replace 似乎去除了整个字符串的空白,这是我不想要的。为什么是这样?我该如何避免?

(例如输出是:

Seattle University
SeattleUniversity
SeattleUniversity
SeattleUniversity
SeattleUniversity
SeattleUniversity
SeattleUniversity
SeattleUniversity
SeattleUniversity
SEATTLEUNIVERSITY

)

最佳答案

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.

这不是一个列表。

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

是一个集合文字。尝试用 [ 和 ] 替换 { 和 } 以获得您想要的顺序。

关于python 字符串替换错误地删除了空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7272758/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com