我有字符串"How are you"
。该字符串应为"How-are-you"
。
正则表达式可能吗?怎么样?
答案 0 :(得分:5)
另一个选项是replace
$ 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
答案 1 :(得分:3)
为什么要使用正则表达式?
x = "How are you"
print "-".join(x.split())
--output:--
How-are-you
答案 2 :(得分:3)
只需使用替换方法中构建的pythons:
strs = "How are you"
new_str = strs.replace(" ","-")
print new_str // "How-are-you"
答案 3 :(得分:2)
正如您所说,使用正则表达式:
>>> import re
>>> s = "How are you"
>>> print re.sub('\s', '-', s)
How-are-you
答案 4 :(得分: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");
请注意,“简单”替换replace可能比使用正则表达式更合适(那些真的功能强大,但在处理之前需要编译阶段,这可能很昂贵。不确定这会对你的程序产生如此简单的影响但是......;)。最后针对一个特例或替换空间序列,没有什么可能超过x.join(str.split())
......