简体   繁体   中英

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 .

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.

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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