Bekalu Tadesse
Bekalu Tadesse

Reputation: 35

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!

Upvotes: 2

Views: 452

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545518

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))

Upvotes: 3

JeffUK
JeffUK

Reputation: 4241

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'

Upvotes: 1

Related Questions