0

I'm creating a web app, and I'm using IMAP to read in strings from an email.

I want to get rid of the new line characters and carriage return characters from the strings in the email. When I've done the relevant IMAP operations and run replace("\n","") on the strings, unfortunately, the strings still have the newline and return carriage characters in them. How can I fix this?

For instance the output for the code below:

try:
    if sender!='craigmac@gmail.com':
        msg  = str(utilities.refineMSG(str(utilities.get_body(raw)))[2:-44]).replace("\r\n",'')
        print(msg)

would be:

Thanks Craig, but we don\'t focus much on medical devices. In particular, we tend to stay away from implantable surgical devices.\r\n\r\nWe\'ll pass on this one for now, but appreciate the heads up.\r\n\r\nBest-\r\n\r\n-Kyle\r\n\r\nsent from my phone\r
MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46

1 Answers1

0

Python's normal str.replace() function can only look for one pattern to replace at a time. So when you call msg.replace('\r\n', ''), you are actually trying to replace all instances where a carriage return is followed by a newline. Instead, chain the replace commands (see answer here):

msg1 = my_email.replace('\r', ' ').replace('\n', ' ')

Another option would be to use regular expressions, which can replace multiple patterns at once:

import re
msg2 = re.sub(r'\r\n', ' ', my_email)
tiberius
  • 430
  • 2
  • 14