Python 删除报价之间不需要的空格

Python 删除报价之间不需要的空格,python,regex,removing-whitespace,Python,Regex,Removing Whitespace,是否有一种更优雅的方法来删除引号之间的空格(尽管使用了如下代码: input = input.replace('" 12 "', '"12"')`) At " 12 " hours " 35 " minutes my friend called me. 从这样一句话: input = input.replace('" 12 "', '"12"')`) At "

是否有一种更优雅的方法来删除引号之间的空格(尽管使用了如下代码:

input = input.replace('" 12 "', '"12"')`)
 At " 12 " hours " 35 " minutes my friend called me.
从这样一句话:

input = input.replace('" 12 "', '"12"')`)
 At " 12 " hours " 35 " minutes my friend called me.

问题是数字可以改变,然后代码就不能正常工作。

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

re.sub(r'"\s*([^"]*?)\s*"', r'"\1"', input)
该模式的内容是“quote,任意数量的空格,不是quote(已捕获)的内容,后跟任意数量的空格和一个quote。替换内容就是您在quote中捕获的内容


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

您可以尝试使用正则表达式,例如下面的正则表达式:

“\s+(.*)\s+”

它匹配任何长度的子字符串,该子字符串包含任何非换行字符,并由空格和引号包围。通过将其传递给
re.compile()
,您可以使用返回的
模式
对象调用
sub()
方法

>>重新导入
>>>string='在“12”小时“35”分钟,我的朋友打电话给我
>>>regex=re.compile(r''\s+(.*?)\s+')
>>>regex.sub(r''\1'',字符串)
“12点35分,我的朋友打电话给我。”

\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.

查看内置的字符串方法
strip()
:)正如@BuddyBob所说,字符串中没有逗号。你是说引号吗?
re.sub(r'+?(.+?)+?,'\\1',s)
,只要字符串的格式是
“什么“
,引号和某物之间的空格将removed@Mark. 谢谢你的帮助。我还想把这个表达写得更仔细一些。我对正则表达式很满意,但它不是我的forte@Stimy:从技术上讲应该是\s*,不是吗?@MadPhysicast我想它可以与
*
+
一起使用,但我首先想到的是
+