【问题标题】:Remove unwanted spaces between quotations删除引号之间不需要的空格
【发布时间】:2021-08-03 08:11:56
【问题描述】:

有没有更优雅的方法来删除引号之间的空格(尽管使用这样的代码:

input = input.replace('" 12 "', '"12"')`)

来自这样的句子:

 At " 12 " hours " 35 " minutes my friend called me.

问题是数字可以更改,然后代码将无法正常工作。 :)

【问题讨论】:

  • 查看内置字符串方法strip() :)
  • 正如@BuddyBob 所说,您的字符串中没有逗号。你的意思是引用吗?
  • re.sub(r'" +?(.+?) +?"', '"\\1"', s)
  • 只要你的字符串格式为" something ",引号之间的空格和一些东西都会被删除

标签: python regex removing-whitespace


【解决方案1】:

这是我快速想出的解决方案,适用于您输入的任何数字。

input = 'At " 12 " hours " 35 " minutes my friend called me.'

input = input.split()

for count, word in enumerate(input):
    if input[count] == '"':
        del input[count]
    if input[count].isdigit():
        input[count] = '"' + input[count] + '"'

str1 = ' '.join(input)
print('Output:')
print(str1)

输出:

>>> Output:
>>> At "12" hours "35" minutes my friend called me.

【讨论】:

    【解决方案2】:

    只要你的引文合理,你就可以使用正则表达式:

    re.sub(r'"\s*([^"]*?)\s*"', r'"\1"', input)
    

    该模式读作“引号,任意数量的空格,不是引号的内容(捕获),后跟任意数量的空格和引号。替换就是您在引号中捕获的内容。

    请注意,捕获组中的量词是不情愿的。这样可以确保您不会捕获尾随空格。

    【讨论】:

    【解决方案3】:

    您可以尝试使用正则表达式,如下所示:

    "\s+(.*?)\s+"

    这匹配任何长度的任何子字符串,其中包含任何不是换行符的字符,由空格和引号包围。通过将此传递给re.compile(),您可以使用返回的Pattern 对象来调用sub() 方法。

    >>> import re
    >>> string = 'At " 12 " hours " 35 " minutes my friend called me.'
    >>> regex = re.compile(r'"\s+(.*?)\s+"')
    >>> regex.sub(r'"\1"', string)
    'At "12" hours "35" minutes my friend called me.'
    

    \1 调用要替换的第一个组,在本例中是与 .*? 匹配的字符串

    【讨论】:

    • 技术上应该是 \s*,不是吗?
    • @MadPhysicist 我想它可以与*+ 一起使用,但我首先想到了+