如何在Python IDLE替换对话框中准确找到“ \ n”?

问题描述 投票:1回答:1

我是Python的入门者,我使它成为RPG的第一批代码之一,因此在字符串中打印了很多文本。在学习如何“自动换行”之前,我曾经测试过每个字符串,并在正确的位置放置“ \ n”,因此最好在控制台中读取历史记录。

但是现在我不再需要那些“ \ n”了,使用Python IDLE的“替换对话框”来替换其中的每一个都是非常费力的。问题之一是我想忽略双换行(“ \ n \ n”),因为它们确实使文本更易于呈现。

因此,如果我只是搜索“ \ n”,他会找到它,但是我想忽略所有的“ \ n \ n”。

我尝试使用“正则表达式”选项,并通过正则表达式进行了研究,但没有成功,因为我在该领域完全陌生。尝试了诸如“ ^ \ n $”之类的事情,因为如果我理解正确,^和$会将搜索范围限制在它们之间。

我认为很明显我需要什么,但是无论如何都会写一个示例:

print("Here's the narrator telling some things to the player. Of course I could do some things but\nnow it's time to ask for help!\n\nProbably it's a simple thing, but it's been lots of time in research and no\nsuccess...")

我想用一个空格(“”)查找并替换这两个“ \ n”,而完全忽略“ \ n \ n”。

你们能帮忙吗?预先感谢。

python regex replace line-breaks
1个回答
0
投票

您需要

re.sub(r'(?<!\n)\n(?!\n)', ' ', text)

详细信息

  • [(?<!\n)-左侧不允许立即使用换行符
  • [\n-换行符
  • [(?!\n)-右侧不允许立即使用换行符

请参见Python demo

import re
text = "Here's the narrator telling some things to the player. Of course I could do some things but\nnow it's time to ask for help!\n\nProbably it's a simple thing, but it's been lots of time in research and no\nsuccess..."
print(re.sub(r'(?<!\n)\n(?!\n)', ' ', text))
© www.soinside.com 2019 - 2024. All rights reserved.