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

发布于 2024-12-02 18:22:26 字数 716 浏览 8 评论 0原文

我有一个方法

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

:)

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

)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

若有似无的小暗淡 2024-12-09 18:22:26

我不明白的是为什么它似乎正在执行“”
在 " of " 替换之前替换,例如,当 " of " 时
替换出现在列表中的空格之前。

这不是一个清单。

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

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

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.

鹿童谣 2024-12-09 18:22:26

字符串上的 Replace 方法将所有出现的第一个参数替换为第二个参数。在循环中,当字符串 word 等于 " " 时,替换方法将删除 searchname" "代码>.

the replace method on a string replaces all occurences of the first argument with the second argument. In your loop, when the string word equals " ", the replace method will delete all occurrences of " " in searchname.

呆头 2024-12-09 18:22:26

也许问题在于 taboo 不是一个列表,它是一个集合,并且集合不保持顺序。

>>> taboo = ['a', 'b', ' ']
>>> print taboo
['a', 'b', ' ']
>>> taboo = {'a', 'b', ' '}
>>> print taboo
set(['a', ' ', 'b'])

Maybe the problem is that taboo is not a list, it is a set and sets do not keep the order.

See

>>> taboo = ['a', 'b', ' ']
>>> print taboo
['a', 'b', ' ']
>>> taboo = {'a', 'b', ' '}
>>> print taboo
set(['a', ' ', 'b'])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文