Python 用连字符替换空格

Python 用连字符替换空格,python,regex,string,Python,Regex,String,我有绳子,你好吗。这根绳子应该变成你好。 用正则表达式可以吗?如何使用?如您所问,使用正则表达式: >>> import re >>> s = "How are you" >>> print re.sub('\s', '-', s) How-are-you 为什么要使用正则表达式 x = "How are you" print "-".join(x.split()) --output:-- How-are-you 只需使用Python

我有绳子,你好吗。这根绳子应该变成你好。
用正则表达式可以吗?如何使用?

如您所问,使用正则表达式:

>>> import re
>>> s = "How are you"
>>> print re.sub('\s', '-', s)
How-are-you
为什么要使用正则表达式

x =  "How are you"
print "-".join(x.split())

--output:--
How-are-you

只需使用Python内置的替换方法:

strs = "How are you"
new_str = strs.replace(" ","-")
print new_str // "How-are-you"

根据您的具体需要,使用正则表达式在该主题上有许多变体:

请注意,简单替换可能比使用正则表达式更合适,因为正则表达式非常强大,但在处理之前需要编译阶段,这可能会非常昂贵。对于这样一个简单的情况,我不确定这是否会真正影响您的程序;。最后,对于一个特殊情况或替换空格序列,没有什么可能比x.joinstr.split更好。

另一个选项是


你试过用“-”替换简单的空格吗?你希望两个空格变成什么?两个空间还是两个空间?空间和\ttab呢?空间和标签还是空间和\ttab?是的,但是aweis以13分钟的优势击败了你,Bryan以2分钟的优势击败了你。“拆分”与“替换”相比有一些优势,例如,如果单词之间可能有多个空格甚至制表符。
# To replace *the* space character only
>>> re.sub(' ', '-', "How are you");

# To replace any "blank" character (space, tab, ...):
>>> re.sub('\s', '-', "How are you");

# To replace any sequence of 1 or more "blank" character (space, tab, ...) by one hyphen:
>>> re.sub('\s+', '-', "How     are             you");

# To replace any sequence of 1 or more "space" by one hyphen:
>>> re.sub(' +', '-', "How     are             you");
$ python -m timeit 'a="How are you"; a.replace(" ", "-")'
1000000 loops, best of 3: 0.335 usec per loop
$ python -m timeit 'a="How are you"; "-".join(a.split())'
1000000 loops, best of 3: 0.589 usec per loop