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

Viewed 156

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!

2 Answers

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, e.g.

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'

Related