有没有更优雅的方法来去除引号之间的空格(而不是使用像这样的代码:
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)
"\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
调用第一组进行替换,即使用 .*?
匹配的字符串
*
或者 +
都可以,但我首先想到的是 +
。 - Jacob Lee这是我快速想出的一个解决方案,适用于您输入的任何数字。
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()
:) - Charles Dupontre.sub(r'" +?(.+?) +?"', '"\\1"', s)
- Tuan Chau"something"
,引号和something之间的空格将被删除。 - Tuan Chau