Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 字符串包含换行符(\n),如何使用正则表达式替换\n到\n?_Python - Fatal编程技术网

Python 字符串包含换行符(\n),如何使用正则表达式替换\n到\n?

Python 字符串包含换行符(\n),如何使用正则表达式替换\n到\n?,python,Python,我只有一根绳子 test = " \n this \nis\n\nto learn \n\n\n regex \n in \n\n python." 我使用re.sub查找并将\n替换为\n,但不起作用 check = re.sub("\n", "\n", test) 预期结果: this is to learn regex in python 还有另一种方法可以做到与上面相同,但如果我将时间消耗与regex进行比较,那么regex将获胜 另一种选择 # I need to loo

我只有一根绳子

test = " \n this \nis\n\nto learn \n\n\n regex \n in \n\n python."
我使用re.sub查找并将\n替换为\n,但不起作用

check = re.sub("\n", "\n", test)
预期结果:

this 
is 
to 
learn
regex
in 
python
还有另一种方法可以做到与上面相同,但如果我将时间消耗与regex进行比较,那么regex将获胜

另一种选择

# I need to loop through every single word in the string plus it doesn't change 
  if I have data like this "\nthis\n\nis" 

check = test.replace("\n", "\n")

您可以尝试将所有空白
\s+
替换为
\n

test = " \n this \nis\n\nto learn \n\n\n regex \n in \n\n python."
output = re.sub(r'\s+', '\n', test).strip()
print(output)
这张照片是:

this
is
to
learn
regex
in
python.

您可以尝试将所有空白
\s+
替换为
\n

test = " \n this \nis\n\nto learn \n\n\n regex \n in \n\n python."
output = re.sub(r'\s+', '\n', test).strip()
print(output)
这张照片是:

this
is
to
learn
regex
in
python.

你希望这能做什么
\n
就是新行在字符串的
repr
中的表示方式,但它们已经是实际的新行了;您所做的是禁止操作。只需使用
print(test)
,您将看到实际渲染的换行。@ShadowRanger仔细查看。有时单词被多个
\n
分隔,还有空格。@TimBiegeleisen:这是他们所展示的,但这不是他们在代码或描述他们意图的散文中所要求的。因此,要求澄清。@ShadowRanger,我想稍后逐行阅读,你希望它做什么
\n
就是新行在字符串的
repr
中的表示方式,但它们已经是实际的新行了;您所做的是禁止操作。只需使用
print(test)
,您将看到实际渲染的换行。@ShadowRanger仔细查看。有时单词被多个
\n
分隔,还有空格。@TimBiegeleisen:这是他们所展示的,但这不是他们在代码或描述他们意图的散文中所要求的。因此,需要澄清。@ShadowRanger,我想稍后逐行阅读是这样用正则表达式(re.sub(“\t”,“test”)擦除“\t”的。我不理解你问这个问题的上下文。我的答案已经删除了
\t
选项卡,并用一个换行符
\n
.re.sub(r'\s+,'\n',test代替了只得到一个。有多个(\n\n)所以我怎么能一次得到它们现在我很困惑。请编辑您的问题并告诉我们真正的问题。我已经为您提供了一个解决方案,可以生成您期望的输出。如果没有空格,\n\n,您提供的代码只会从(\n\n)更改一个并提醒仍然存在\n.I断点代码,以了解它在可视化代码编辑器中的一步一步工作方式是使用regex擦除“\t”(re.sub(“\t”,“test”)我不明白你问这个问题的背景。我的答案已经删除了
\t
选项卡,并用一行换行符替换。re.sub(r'\s+','\n',test)只得到一个。有多个(\n\n)那么我怎样才能一次获得所有这些内容呢?现在我很困惑。请编辑您的问题并告诉我们真正的问题。我已经为您提供了一个解决方案,可以生成您期望的输出。如果没有空格,您提供的代码只会更改一个(\n\n)并提醒仍然存在\n.I断点代码,以便在可视化代码编辑器中逐步了解其工作方式