如何使用Python格式化字符串



我得到了一个字符串,如下所示

s = 'This is sentence 1."This is sentence 2." This is sentence 3.'

我希望输出如下

This is sentence 1.
"This is sentence 2."
This is sentence 3.

我已经为这个写了以下代码

s = 'This is sentence 1."This is sentence 2." This is sentence 3.'
for i in s.replace('.','.n').split('n'):
print(i.strip())

下面是我得到的输出

This is sentence 1.
"This is sentence 2.
" This is sentence 3.

问题出在一个双引号的句子上。

我认为如果我能写一个可以区分的正则表达式,那么可以用正则表达式做一些事情。和"然后我就可以解决我的问题了。

如果这是您需要解决的确切情况,则以下代码将执行此操作:

import re
s = 'This is sentence 1."This is sentence 2." This is sentence 3.'
output = re.findall("This.is.sentence.d.", s)
output[1] = '"' + output[1] + '"'
for i in range(0, len(output)):
print(output[i])

否则,将需要使用不同的方法。

我会给你一个提示。尝试添加一个IF语句,让您的代码决定要执行的操作。这是为了防止您希望将代码与更大的字符串一起使用。

对于一般情况(任何数量的句子,其中任何数量都可以被引用(,解决这个问题实际上相当复杂,尤其是如果双引号不仅可以出现在句子周围,而且可以出现在句中。我认为这个代码有效,但我对它并不完全满意:

import re
s = 'Some sentence. Another sentence. "A quoted sentence." A "sentence" containing quotes. Yet another sentence.'
rx = re.compile(r'"[^"]+?."s*|[^"].+?.s*')
r = re.match(rx, s)
while r:
print(r.group(0))
s = re.sub(rx, '', s, 1)
r = re.match(rx, s)

最新更新