【问题标题】:python join single characters in stringpython加入字符串中的单个字符
【发布时间】:2019-05-17 10:53:39
【问题描述】:

输入:

str1 = "a b abcd a b"

期望的输出:

"ab abcd ab"

如何仅删除字符串单个字符之间的空格?

我想我不能使用 split 和 join 因为它会标记所有然后不会关心子字符串的长度。

【问题讨论】:

    标签: python join split


    【解决方案1】:

    这是一个使用re.sub 的选项。我们可以匹配以下模式:

    (?<=\b[a-z]) (?=[a-z]\b)
    

    然后用空字符串替换,删除目标空间。

    input = "a b abcd a b"
    output = re.sub(r'(?<=\b[a-z]) (?=[a-z]\b)', '', input)
    print(output)
    
    ab abcd ab
    

    使用的正则表达式模式表示:

    (?<=\b[a-z])   assert that what precedes is a single letter, which itself
                   is preceded by a word boundary
    [ ]            match a single space (brackets used for clarity only)
    (?=[a-z]\b)    assert that what follows is also a single letter, which again
                   is followed by a word boundary
    

    【讨论】:

      【解决方案2】:

      你也可以反过来想:填充长字符串

      def padLong(item):
          if len(item) == 1:
              return item
          return ' ' + item + ' '
      
      str1 = "a b abcd a b abc abcd"
      
      strs = str1.split()
      print(strs)
      
      strs = ''.join([padLong(item) for item in strs])
      print(strs)
      
      strs = strs.split()
      strs = ' '.join(strs)
      print(strs)
      

      输出:

      ['a', 'b', 'abcd', 'a', 'b', 'abc', 'abcd']
      ab abcd ab abc  abcd 
      ab abcd ab abc abcd
      

      【讨论】:

        猜你喜欢
        • 2013-06-07
        • 2017-11-20
        • 2014-07-30
        • 2013-07-20
        • 1970-01-01
        • 2017-04-19
        • 2015-02-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多