我想在字符串中用下划线替换空白,以创建良好的url。例如:
"This should be connected"
应该成为
"This_should_be_connected"
我使用Python和Django。这可以用正则表达式解决吗?
我想在字符串中用下划线替换空白,以创建良好的url。例如:
"This should be connected"
应该成为
"This_should_be_connected"
我使用Python和Django。这可以用正则表达式解决吗?
当前回答
替换空格是可以的,但我建议进一步处理其他不利于url的字符,如问号、撇号、感叹号等。
还要注意,搜索引擎优化专家的普遍共识是,在url中,破折号比下划线更受欢迎。
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的字符,如问号、撇号、感叹号等。
还要注意,搜索引擎优化专家的普遍共识是,在url中,破折号比下划线更受欢迎。
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!"))
Django有一个“slugify”函数可以做到这一点,还有其他url友好的优化。它隐藏在defaultfilters模块中。
>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")
this-should-be-connected
这并不完全是您所要求的输出,但在我看来,它更适合在url中使用。
mystring.replace (" ", "_")
如果你将这个值赋给任何变量,它都可以工作
s = mystring.replace (" ", "_")
默认情况下mystring不会有这个
使用字符串的replace方法:
“这应该是有联系的”。Replace (" ", "_")
“this_should_be_disconnected”。Replace ("_", " ")
你不需要正则表达式。Python有一个内置的string方法,可以满足你的需要:
mystring.replace(" ", "_")