【问题标题】:Replacing spaces with hyphens [duplicate]用连字符替换空格[重复]
【发布时间】:2013-08-11 16:59:52
【问题描述】:

我有字符串"How are you"。这个字符串应该变成"How-are-you"。 正则表达式可以吗?怎么样?

【问题讨论】:

  • 你有没有试过用'-'查看简单的替换空间。
  • 你想让"Two spaces"变成什么? "Two--spaces" 还是 "Two-spaces""space and\ttab" 呢? "space-and-tab""space-and\ttab"?

标签: python regex string


【解决方案1】:

另一个选项是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

【讨论】:

  • 是的,但是 aweis 以 13 分钟和 2 分钟的优势击败了您。 split() 比 replace() 有一些优势,例如如果单词之间可能有多个空格甚至制表符。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    为什么要使用正则表达式?

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

    【讨论】:

      【解决方案4】:

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

      >>> import re
      >>> s = "How are you"
      >>> print re.sub('\s', '-', s)
      How-are-you
      

      【讨论】:

        【解决方案5】:

        根据您的具体需求,该主题有很多变体使用正则表达式

        # 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())...

        【讨论】:

          猜你喜欢
          • 2012-09-29
          • 1970-01-01
          • 1970-01-01
          • 2015-03-27
          • 2020-12-15
          • 2014-03-16
          • 2011-07-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多