python - 如何在Python IDLE替换对话框中准确找到 "\n"?

标签 python regex replace line-breaks

我是 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”。

你们能帮忙吗?提前致谢。

最佳答案

你需要

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

请参阅regex demo .

详细信息

  • (?<!\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))

输出:

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 - 如何在Python IDLE替换对话框中准确找到 "\n"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61416238/

相关文章:

python - 在Python中从txt文件中读取列表

javascript - 在javascript中使用正则表达式从字符串中提取 double 和整数

replace - 崇高文本 : interactive confirm for replace?

java - 从文本文件的一行中删除单词

regex - 如何仅使用公式在 Excel 或 Google Sheets 中获取 2 个不同字符之间的电子邮件地址?

java - 为什么 replaceAll ("$","") 不起作用,尽管 replace ("$","") 工作得很好?

python - 你如何使用 pip、virtualenv 和 Fabric 来处理部署?

Python mysql 错误

python - 如何保证数据完整发送? sendto(udp套接字)Python

c++ - 使用 Boost::Xpressive 匹配单个字符