【问题标题】:Find and replace multiple comma/space instances in a string, Python查找和替换字符串中的多个逗号/空格实例,Python
【发布时间】:2016-03-02 17:40:57
【问题描述】:

我有一个字符串,其中包含多个连续的,(逗号+空格)实例,我想用单个实例替换它。有干净的方法吗?我想 RegEx 会有所帮助。

一个天真的例子:

s = 'a, b, , c, , , d, , , e, , , , , , , f

想要的输出:

'a, b, c, d, e, f

当然,文本可以改变,所以搜索应该是,连续个实例。

【问题讨论】:

  • 你是怎么得到如此均匀的位移的?
  • 不确定我是否理解这个问题。这是其他东西的简化示例:)

标签: python regex string python-3.x text


【解决方案1】:

因此,正则表达式搜索 两个或更多,(逗号 + 空格)实例,然后在 sub 函数中将其替换为一个 ,

import re
pattern = re.compile(r'(,\s){2,}')

test_string = 'a, b, , c, , , d, , , e, , , , , , , f'
print re.sub(pattern, ', ', test_string)
>>> a, b, c, d, e, f

并且没有正则表达式(正如 @Casimir et Hippolyte 在评论中建议的那样)

test_string = 'a, b, , c, , , d, , , e, , , , , , , f'
test_string_parts = test_string.split(',')
test_string_parts = [part.strip() for part in test_string_parts if part != ' ']
print ', '.join(test_string_parts)
>>> a, b, c, d, e, f

【讨论】:

  • 谢谢。这不一样吗:re.sub(r'(,\s){2,}', ', ', test_string)?或者,是否有一些显着的差异或极端情况?
  • 它也可以。更多关于compile的信息在这里:stackoverflow.com/questions/452104/…
  • 如果我有', ' 而不是'\n' 我将如何调整这个查找和替换? (\\n){2,} 似乎在 regex101.com 中有效,但在 Python 中无效。有什么建议吗?
  • 为什么不只是r'\n{2,}'
  • 试过r'\n{2,}'。它无法在 Python 和 regex101.com 中捕获 '\n '
【解决方案2】:

你可以使用reduce:

>>> from functools import reduce
>>> reduce( (lambda x, y: x+', '+y if y else x), s.split(', '))

(其中 x 是进位,y 是项目)

【讨论】:

    【解决方案3】:

    解决您的问题的最简单方法是:

    >>> s = 'a, b, , c, , , d, , , e, , , , , , , f'
    >>> s = [x for x in s if x.isalpha()]
    >>> print(s)
    ['a', 'b', 'c', 'd', 'e', 'f']
    

    然后,使用 join()

    >>> ', '.join(s)
    'a, b, c, d, e, f'
    

    一行完成:

    >>> s = ', '.join([x for x in s if x.isalpha()])
    >>> s
    'a, b, c, d, e, f'
    

    另辟蹊径:

    >>> s = 'a, b, , c, , , d, , , e, , , , , , , f'
    >>> s = s.split()  #split all ' '(<- space)
    >>> s
    ['a,', 'b,', ',', 'c,', ',', ',', 'd,', ',', ',', 'e,', ',', ',', ',', ',', ',', ',', 'f']
    >>> while ',' in s:
    ...     s.remove(',')
    >>> s
    ['a,', 'b,', 'c,', 'd,', 'e,', 'f']
    >>> ''.join(s)
    'a,b,c,d,e,f'
    

    【讨论】:

    • 但是...这仅适用于单字母变量...请阅读问题:)
    • 只需添加一个新方法
    【解决方案4】:
    s = ", , a, b, , c, , , d, , , e, , , ,  , , , f,,,,"
    s = [o for o in s.replace(' ', '').split(',') if len(o)]
    print (s)
    

    【讨论】:

    • 这个答案来自低质量的帖子。即使代码是不言自明的,也要添加一些解释
    【解决方案5】:

    另一种解决方案:通过列表和相同列表的组合,移动一个(换句话说,通过连续项目对)并从第一个(前一个)项目不同于的每一对中选择第二个项目第二个(下一个)项目:

    s = 'a. b. . c. . . d. . . e. . . . . . . f'
    test = []
    for i in s:
        if i != ' ':
            test.append(i)
    
    
    res = [test[0]] + [y for x,y in zip(test, test[1:]) if x!=y]
    
    for x in res:
        print(x, end='')
     
    

    产量

    a.b.c.d.e.f
    [Program finished]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 2015-06-19
      • 2023-01-31
      • 2019-07-19
      • 2019-04-24
      相关资源
      最近更新 更多