简体   繁体   English

如何替换字符串中的 `\n` 而不是 Python 中的 `\n\n`?

[英]How do I replace `\n` in a string but not `\n\n` in Python?

I have the following string:我有以下字符串:

mystring = '\n\nAvailability:\n  Open source,  \n\nResource Name:\n  QIIME  \n\nResource ID:\n                        SCR_008249'

I wanted to replace \n from the above string, but not \n\n .我想从上面的字符串中替换\n ,但不是\n\n

So I tried this:所以我尝试了这个:

new_string = " ".join(mystring.split())

And found this:并发现了这个:

'Availability: Open source, Resource Name: QIIME, Resource ID: SCR_008249'

But I wanted something like this:但我想要这样的东西:

'Availability: Open source, 
 Resource Name: QIIME Resource 
 ID: SCR_008249'

Thanks!谢谢!

You can use regex:您可以使用正则表达式:

import re

print(re.sub(r'\n(\n)?', r'\1', mystring))

This solves your stated problem.这解决了你所说的问题。 However, the output looks different from your output, because your output does not conform to your requirement.但是,output 看起来与您的 output 不同,因为您的 output 不符合您的要求。

If you also want to normalise whitespace, throw in some whitespace-sponging pattern, eg如果您还想规范化空白,请输入一些空白模式,例如

print(re.sub(r'\n(\n)? *', r'\1 ', mystring))

One option is to split it by \n\n\ , remove the \n from each part, then put it back together again:一种选择是将其拆分为\n\n\ ,从每个部分中删除\n ,然后将其重新组合在一起:

mystring = '\n\nAvailability:\n  Open source,  \n\nResource Name:\n  QIIME  \n\nResource ID:\n                        SCR_008249'

new_string = "\n\n".join([x.replace("\n","") for x in mystring.split("\n\n")])

print(repr(new_string))

output: output:

'\n\nAvailability: Open source, \n\nResource Name: QIIME \n\nResource ID: SCR_008249'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM