在python中,如何在字符串中的“.[xxx]”等每个字符后添加换行符

2024-06-26 01:58:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的绳子:

It reported the proportion of the edits made from America was 51% for the Wikipedia, and 25% for the simple Wikipedia.[142] The Wikimedia Foundation hopes to increase the number in the Global South to 37% by 2015.[143]

我正在尝试用.[xxx] \n替换像这个.[xxx]这样的每个字符

这里是数字

我正从不同的答案中寻求帮助,其中之一就是:

Python insert a line break in a string after character "X"

Regex: match fullstop and one word in python

^{pr2}$

我期望以下输出:

It reported the proportion of the edits made from America was 51% for the Wikipedia, and 25% for the simple Wikipedia.[142]                          
The Wikimedia Foundation hopes to increase the number in the Global South to 37% by 2015.[143]”

但我得到了:

It reported the proportion of the edits made from America was 51% for the Wikipedia, and 25% for the simple Wikipedia\\.\[[0-9]{2,5}\]\s   The Wikimedia Foundation hopes to increase the number in the Global South to 37% by 2015\\.\[[0-9]{2,5}\]\s

Tags: andofthetoinfromforit
3条回答

你可以用

(\.\[[^][]*\])\s*

并将其替换为\1\n,请参见a demo on regex101.com


上面写着 ^{pr2}$

使用findall()来标识匹配模式的列表。然后可以将其替换为原始字符串+'\n'

您可能想在re.sub中使用捕获组和反向引用。您也不需要转义替换字符串(regex101):

import re
s = '''It reported the proportion of the edits made from America was 51% for the Wikipedia, and 25% for the simple Wikipedia.[142] The Wikimedia Foundation hopes to increase the number in the Global South to 37% by 2015.[143] '''
x = re.sub(r'\.\[([0-9]{2,5})\]\s', r'.[\1] \n', s)
print(x)

印刷品:

^{pr2}$

相关问题 更多 >