python 字符串替换错误地删除了空格
我有一个方法
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是一个清单。
是一个集合文字。尝试用 [ 和 ] 替换 { 和 } 以获得您想要的顺序。
It's not a list.
is a set literal. Try replacing { and } by [ and ] to get the order you want.
字符串上的 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" "
insearchname
.也许问题在于
taboo
不是一个列表,它是一个集合,并且集合不保持顺序。看
Maybe the problem is that
taboo
is not a list, it is a set and sets do not keep the order.See