是否有更优雅的方法来删除引号之间的空格(尽管使用了这样的代码:
input = input.replace('" 12 "', '"12"')`)
来自这样一句话:
At " 12 " hours " 35 " minutes my friend called me.
问题是,数字可能会改变,然后代码将无法正常工作。:(
只要引号合理,就可以使用正则表达式:
re.sub(r'"s*([^"]*?)s*"', r'"1"', input)
图案读作";引号,任意数量的空格,不是引号的东西(捕获(,后面跟着任意数量的空间和引号。替换只是你在引号中捕捉到的东西。
请注意,捕获组中的量词是不情愿的。这样可以确保不会捕获尾部空格。
您可以尝试使用正则表达式,例如下面的表达式:
"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
调用要替换的第一组,在这种情况下是.*?
匹配的字符串
这是我快速提出的一个解决方案,适用于您输入的任何数字。
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.