如何在 Python IDLE 替换对话框中准确找到“\n”?
How to find exactly "\n" in Python IDLE replace dialog?
我是 Python 的初学者,我制作的第一批代码之一是 RPG,因此打印的字符串中有很多文本。在学习如何 "word wrap" 之前,我曾经测试过每个字符串并在正确的位置放置一个“\n”,因此在控制台中读取历史记录可能会更好。
但现在我不再需要那些“\n”了,使用Python IDLE 的替换对话框来替换它们真的很费力。问题之一是我想忽略双换行符 ("\n\n"),因为它们确实使文本更美观。
所以如果我只搜索“\n”他就找到了,但我想忽略所有的“\n\n”。
我尝试使用 "Regular expression" 选项并使用正则表达式进行了研究,但没有成功,因为我在这个领域完全陌生。尝试了 "^\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”并将其替换为一个空的 space(“”),完全忽略“\n\n”。
你们能帮忙吗?提前致谢。
你需要
re.sub(r'(?<!\n)\n(?!\n)', ' ', text)
参见regex demo。
详情
(?<!\n)
- 左边不允许换行
\n
- 一个换行符
(?!\n)
- 右边不允许换行
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))
输出:
Here's the narrator telling some things to the player. Of course I could do some things but now it's time to ask for help!
Probably it's a simple thing, but it's been lots of time in research and no success...
我是 Python 的初学者,我制作的第一批代码之一是 RPG,因此打印的字符串中有很多文本。在学习如何 "word wrap" 之前,我曾经测试过每个字符串并在正确的位置放置一个“\n”,因此在控制台中读取历史记录可能会更好。
但现在我不再需要那些“\n”了,使用Python IDLE 的替换对话框来替换它们真的很费力。问题之一是我想忽略双换行符 ("\n\n"),因为它们确实使文本更美观。
所以如果我只搜索“\n”他就找到了,但我想忽略所有的“\n\n”。
我尝试使用 "Regular expression" 选项并使用正则表达式进行了研究,但没有成功,因为我在这个领域完全陌生。尝试了 "^\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”并将其替换为一个空的 space(“”),完全忽略“\n\n”。
你们能帮忙吗?提前致谢。
你需要
re.sub(r'(?<!\n)\n(?!\n)', ' ', text)
参见regex demo。
详情
(?<!\n)
- 左边不允许换行\n
- 一个换行符(?!\n)
- 右边不允许换行
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))
输出:
Here's the narrator telling some things to the player. Of course I could do some things but now it's time to ask for help!
Probably it's a simple thing, but it's been lots of time in research and no success...