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

"This should be connected" 

应该成为

"This_should_be_connected" 

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


当前回答

perl -e 'map { $on=$_; s/ /_/; rename($on, $_) or warn $!; } <*>;'

匹配和替换当前目录下所有文件的空格>下划线

其他回答

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

如果你将这个值赋给任何变量,它都可以工作

s = mystring.replace (" ", "_")

默认情况下mystring不会有这个

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

string.replace(old, new)

所以你可以用:

string.replace(" ", "_")

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

使用字符串的replace方法:

“这应该是有联系的”。Replace (" ", "_")

“this_should_be_disconnected”。Replace ("_", " ")

这考虑了空白字符而不是空格,我认为它比使用re模块更快:

url = "_".join( title.split() )