Luc*_*cas 184 python regex django
我想用字符串中的下划线替换空格来创建漂亮的URL.例如:
"This should be connected" becomes "This_should_be_connected"
Run Code Online (Sandbox Code Playgroud)
我正在使用Python与Django.这可以使用正则表达式解决吗?
rog*_*pvl 313
您不需要正则表达式.Python有一个内置的字符串方法,可以满足您的需求:
mystring.replace(" ", "_")
Run Code Online (Sandbox Code Playgroud)
Tri*_*ych 71
替换空格很好,但我可能会建议更进一步处理其他URL恶意字符,如问号,撇号,感叹号等.
另请注意,SEO专家的普遍共识是破折号优先于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!"))
Run Code Online (Sandbox Code Playgroud)
Dan*_*man 39
Django具有"slugify"功能,可以执行此操作,以及其他对URL友好的优化.它隐藏在defaultfilters模块中.
>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")
this-should-be-connected
Run Code Online (Sandbox Code Playgroud)
这不是您要求的输出,但IMO最好用于URL.
xOn*_*eca 35
这考虑了空格以外的空白字符,我认为它比使用re模块更快:
url = "_".join( title.split() )
Run Code Online (Sandbox Code Playgroud)
Jar*_*die 17
使用re模块:
import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And so\tshould this') # And_so_should_this
Run Code Online (Sandbox Code Playgroud)
除非您有如上所述的多个空格或其他空白可能性,否则您可能希望string.replace像其他人建议的那样使用.
mdi*_*olf 10
使用string的替换方法:
"this should be connected".replace(" ", "_")
"this_should_be_disconnected".replace("_", " ")
小智 6
Python 有一个名为 replace 的内置字符串方法,其用法如下:
string.replace(old, new)
Run Code Online (Sandbox Code Playgroud)
所以你会使用:
string.replace(" ", "_")
Run Code Online (Sandbox Code Playgroud)
不久前我遇到了这个问题,我编写了代码来替换字符串中的字符。我必须开始记住检查 python 文档,因为它们已经为所有内容内置了函数。
我将以下代码用于我的友好网址:
from unicodedata import normalize
from re import sub
def slugify(title):
name = normalize('NFKD', title).encode('ascii', 'ignore').replace(' ', '-').lower()
#remove `other` characters
name = sub('[^a-zA-Z0-9_-]', '', name)
#nomalize dashes
name = sub('-+', '-', name)
return name
Run Code Online (Sandbox Code Playgroud)
Unicode字符也可以正常工作。
令人惊讶的是,这个图书馆还没有提到
名为python-slugify的python包,可以很好地完成slugizing:
pip install python-slugify
Run Code Online (Sandbox Code Playgroud)
像这样工作:
from slugify import slugify
txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = "This -- is a ## test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")
txt = 'C\'est déjà l\'été.'
r = slugify(txt)
self.assertEquals(r, "cest-deja-lete")
txt = 'Nín h?o. W? shì zh?ng guó rén'
r = slugify(txt)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")
txt = '?????????'
r = slugify(txt)
self.assertEquals(r, "kompiuter")
txt = 'jaja---lol-méméméoo--a'
r = slugify(txt)
self.assertEquals(r, "jaja-lol-mememeoo-a")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
256414 次 |
| 最近记录: |