我想在字符串中用下划线替换空格,以创建漂亮的URL。例如:
"This should be connected"
应该变成什么
"This_should_be_connected"
我正在使用Python和Django。这个问题能用正则表达式解决吗?
你不需要使用正则表达式。Python有一个内置的字符串方法可以实现你所需的功能:
mystring.replace(" ", "_")
re.sub(r"\s+", '', content)
。 - Macbricimport 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!"))
这个方法考虑了除空格以外的空白字符,而且我认为它比使用re
模块更快:
url = "_".join( title.split() )
Django有一个名为“slugify”的函数,可以执行此操作,以及其他适合于URL的优化。它被隐藏在defaultfilters模块中。
>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")
this-should-be-connected
这并不完全是你要求的输出,但在我看来,它更适合用于URL。
使用 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
除非你有多个空格或其他上述可能的空白字符,你可以像其他人建议的那样使用 string.replace
。
'\s+'
替换为r'\s+'
。详情请见:https://www.flake8rules.com/rules/W605.html - mrroot5使用字符串的替换方法:
"这应该连接".replace(" ", "_")
"这_应该_断开".replace("_", " ")
mystring.replace(r' ','-')
令人惊讶的是,这个库还没有被提到过。
python-slugify是一个Python包,它对slugify做了非常好的处理:
pip install python-slugify
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")
Python中的字符串有一个内置方法叫做replace,用法如下:
string.replace(old, new)
因此,您可以使用:
string.replace(" ", "_")
我之前遇到了这个问题,写了一些代码来替换字符串中的字符。现在我得开始记住要检查Python文档,因为它们有针对所有情况的内置函数。
我使用以下代码来生成友好的URL:
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
它也可以很好地处理Unicode字符。
slugify
不能提供所需的输出。 - user1144616