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

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)

  • 这不适用于其他空白字符,例如\ t或不间断空格. (24认同)
  • 是的,你是对的,但出于问题的目的,似乎没有必要考虑其他空间. (11认同)
  • 不适用于不间断空格,请改用 `re.sub(r"\s+", '', content)` (6认同)
  • 这个答案可能会令人困惑,最好把它写成mystring = mystring.replace("","_"),因为它不直接改变字符串而是返回一个更改的版本. (4认同)
  • 我需要导入任何东西才能使其工作吗?我收到以下错误: AttributeError: 'builtin_function_or_method' object has no attribute 'replace' (2认同)
  • 可能是您调用的变量替换,不是字符串类型. (2认同)

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)

  • @Triptych你是什么意思?非洲或欧洲的燕子? (2认同)

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.

  • @Lulu人使用短划线,因为很长一段时间,搜索引擎将破折号视为单词分隔符,因此您可以更轻松地进行多字搜索. (3认同)

xOn*_*eca 35

这考虑了空格以外的空白字符,我认为它比使用re模块更快:

url = "_".join( title.split() )
Run Code Online (Sandbox Code Playgroud)

  • 更重要的是,它适用于任何空白字符或空白字符组. (4认同)
  • 正则表达式 > 拆分/连接 > 替换 (2认同)

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像其他人建议的那样使用.

  • PEP8 将“\s+”替换为“r”\s+”。信息:https://www.flake8rules.com/rules/W605.html (2认同)

mdi*_*olf 10

使用string的替换方法:

"this should be connected".replace(" ", "_")

"this_should_be_disconnected".replace("_", " ")


小智 9

你可以尝试这个:

mystring.replace(r' ','-')
Run Code Online (Sandbox Code Playgroud)


小智 6

Python 有一个名为 replace 的内置字符串方法,其用法如下:

string.replace(old, new)
Run Code Online (Sandbox Code Playgroud)

所以你会使用:

string.replace(" ", "_")
Run Code Online (Sandbox Code Playgroud)

不久前我遇到了这个问题,我编写了代码来替换字符串中的字符。我必须开始记住检查 python 文档,因为它们已经为所有内容内置了函数。


Arm*_*das 5

我将以下代码用于我的友好网址:

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字符也可以正常工作。


Yas*_*ash 5

令人惊讶的是,这个图书馆还没有提到

名为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)