我想在字符串中用下划线替换空白,以创建良好的url。例如:

"This should be connected" 

应该成为

"This_should_be_connected" 

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


当前回答

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

mystring.replace(" ", "_")

其他回答

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

mystring.replace(" ", "_")

我使用下面的一段代码为我的友好网址:

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字符。

使用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。按照其他人的建议替换。

Python在字符串上有一个内置的方法,叫做replace,它的用法如下:

string.replace(old, new)

所以你可以用:

string.replace(" ", "_")

我以前遇到过这个问题,我写了代码来替换字符串中的字符。我必须开始记得检查python文档,因为它们为所有东西都内置了函数。

x = re.sub("\s", "_", txt)