import re
def urlify(s):
# Remove all non-word characters (everything except numbers and letters)
s = re.sub(r"[^\w\s]", '', s)
# Replace all runs of whitespace with a single dash
s = re.sub(r"\s+", '-', s)
return s
# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))
替换空格是可以的,但是我可能建议进一步处理其他不适合URL的字符,如问号、撇号、感叹号等
还要注意,SEO专家的普遍共识是dashes are preferred to underscores in URLs.
你不需要正则表达式。Python有一个内置的字符串方法,可以满足您的需要:
Django有一个“slugify”函数来实现这一点,以及其他URL友好的优化。它隐藏在defaultfilters模块中。
这并不完全是您要求的输出,但在IMO中,它更适合用于url。
相关问题 更多 >
编程相关推荐