Question: I have extracted an email and save it to a text file that is not properly formatted. How to remove unwanted line spacing and paragraph spacing?

The file looks like this:

```
                Hi Kim,

                     Hope you are fine.

                  Your Code is:

                    42483423

                 Thanks and Regards,

                    Bolt

```

I want to open and edit this file and arrange it in a proper format removing all the spaces before the text and below the text in the proper format like:

```
Hi Kim,
Hope you are fine.
Your Code is:
42483423
Thanks and Regards,
Bolt

```

My start procedure,

```
file = open('email.txt','rw')

```

Answer: 
You can use `re.sub`:

```
import re
re.sub('\s\s+', '\n', s)

```
If you have the entire text in a single string (`s`), you could do something like this:

```
formatted = "\n".join(filter(None, (x.strip() for x in s.split("\n"))))

```

That:

* splits the string into separate lines
* strips any leading and trailing whitespace
* filters out empty strings
* rejoins into a multi-line string

Result:

```
Hi Kim,
Hope you are fine.
Your Code is:
42483423
Thanks and Regards,
Bolt

```