【问题标题】:How to replace all the whitespaces in a string if the whitespaces are surrounded by quotes in Python?如果空格在Python中被引号包围,如何替换字符串中的所有空格?
【发布时间】:2020-10-08 02:36:05
【问题描述】:

我有一个清单 l。

l = ["This is","'the first 'string","and 'it is 'good"]

我想用“|space|”替换所有的空格在 's 内的字符串中。

print (l)
# ["This is","'the|space|first|space|'string","and 'it|space|is|space|'good"]

我不能在 for 循环中使用 for 循环并直接使用 .replace() 因为字符串是不可变的

TypeError: 'str' 对象不支持项目分配

我看过以下问题,但没有一个对我有帮助。

在for循环Python中替换字符串元素(3个答案)

在 for 循环中运行 replace() 方法? (3 个回答)

使用列表理解替换字符串(7 个答案)

我考虑过使用 re.sub,但想不出合适的正则表达式来完成这项工作。

【问题讨论】:

  • 我很确定正则表达式在这种情况下不起作用。我认为使用引号作为分隔符拆分字符串然后使用字符串替换会更容易。

标签: python regex string list replace


【解决方案1】:

这对我有用:

>>> def replace_spaces(str) :
...     parts = str.split("'")
...     for i in range(1,len(parts),2) :
...         parts[i] = parts[i].replace(' ', '|')
...     return "'".join( parts )
... 
>>> [replace_spaces(s) for s in l]
['This is', "'the|first|'string", "and 'it|is|'good"]
>>> 

【讨论】:

  • 感谢您提供简单的解决方案!我不敢相信我没有想到这一点。
【解决方案2】:

我想我已经用正则表达式解决了你的替换问题。您可能需要进一步完善给定的代码 sn-p 以满足您的需要。

如果我正确理解了这个问题,诀窍是使用正则表达式来找到要替换的正确空间。

match = re.findall(r"\'(.+?)\'", k) #here k is an element in list.

放置骨架代码供您参考:

import re

l = ["This is","'the first 'string","and 'it is 'good"]

#declare output

for k in l:
    match = re.findall(r"\'(.+?)\'", k)
    if not match:
        #append k itself to your output
    else:
        p = (str(match).replace(' ', '|space|'))
        #append p to your output

我还没有测试它,但它应该可以工作。如果您遇到任何问题,请告诉我。

【讨论】:

    【解决方案3】:

    使用regex text-munging

    import re
    
    l = ["This is","'the first 'string","and 'it is 'good"]
    
    def repl(m):
      return m.group(0).replace(r' ', '|space|')
    
    l_new = []
    for item in l:
      quote_str = r"'.+'"
      l_new.append(re.sub(quote_str, repl, item))
    
    
    print(l_new)
    

    输出:

    ['This is', "'the|space|first|space|'string", "and 'it|space|is|space|'g
    ood"]
    

    完整的逻辑基本上是:

    1. 循环遍历l 的元素。
    2. 找到string between single quotes。将其传递给repl 函数。
    3. repl 函数我使用简单的replace 替换spaces with |space|

    文本处理参考 => https://docs.python.org/3/library/re.html#text-munging

    【讨论】:

      猜你喜欢
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 2015-08-25
      相关资源
      最近更新 更多