如何将空格替换为下划线,反之亦然?

2024-04-25 09:43:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用字符串中的下划线替换空白来创建漂亮的url。例如:

"This should be connected" becomes "This_should_be_connected" 

我在Django中使用Python。这可以用正则表达式来解决吗?


Tags: django字符串urlbethis空白shouldconnected
3条回答

替换空格是可以的,但是我可能建议进一步处理其他不适合URL的字符,如问号、撇号、感叹号等

还要注意,SEO专家的普遍共识是dashes are preferred to underscores in URLs.

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!"))

你不需要正则表达式。Python有一个内置的字符串方法,可以满足您的需要:

mystring.replace(" ", "_")

Django有一个“slugify”函数来实现这一点,以及其他URL友好的优化。它隐藏在defaultfilters模块中。

>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")

this-should-be-connected

这并不完全是您要求的输出,但在IMO中,它更适合用于url。

相关问题 更多 >