python - 如何在python中的字符串中的每个字符后添加换行符,如“.[xxx]”
问题描述
我有以下字符串:
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]
用.[xxx] \n
;替换每个这样的字符
x 是这里的数字
我正在从不同的茎溢出答案中获得帮助;其中之一是:
import re
str = "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("\.\[[0-9]{2,5}\]\s", "\.\[[0-9]{2,5}\]\s\n",str)
print(x)
我期望以下输出:
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
解决方案
您可能希望在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)
印刷:
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]
推荐阅读
- django - 如何在 django 中只获得多对多关系的结果
- reactjs - 没有从 redux thunk 获取同步数据
- webpack - 自动前缀在 webpack 中不起作用
- python - 使用 Python For 循环找不到的“不可见文件”
- c# - 一个类为另一个类注册事件处理程序是不好的做法吗?
- c - C 程序的语言环境如何设置为“C”语言环境?
- azure - CosmosDB 中的索引数组
- c# - 如何使用 C# 在单击按钮时将同一图片的另一张图片添加到我的表单中?
- python - 减少数据框行和查找
- json - 使用 HttpClient 在 Angular 中通过外部 API 访问 Json 数据