简体   繁体   English

摆脱 python 中的换行符和回车符

[英]Getting rid of new line and carriage return characters in python

I'm creating a web app, and I'm using IMAP to read in strings from an email.我正在创建一个 web 应用程序,并且我正在使用 IMAP 从 email 中读取字符串。

I want to get rid of the new line characters and carriage return characters from the strings in the email.我想从 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.当我完成相关的 IMAP 操作并在字符串上运行replace("\n","")时,不幸的是,字符串中仍然有换行符和回车符。 How can I fix this?我怎样才能解决这个问题?

For instance the output for the code below:例如下面代码的 output:

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

Python's normal str.replace() function can only look for one pattern to replace at a time. Python 的普通 str.replace str.replace() function 一次只能查找一个要替换的模式。 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.因此,当您调用msg.replace('\r\n', '')时,您实际上是在尝试替换所有回车后跟换行符的实例。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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