我正在创建一个web应用程序,并使用IMAP从电子邮件中读取字符串
我想去掉电子邮件中字符串中的新行字符和回车字符。当我完成了相关的IMAP操作并对字符串运行replace("\n","")
时,不幸的是,字符串中仍然包含换行符和回车符。我怎样才能解决这个问题
例如,下面代码的输出:
try:
if sender!='craigmac@gmail.com':
msg = str(utilities.refineMSG(str(utilities.get_body(raw)))[2:-44]).replace("\r\n",'')
print(msg)
将是:
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的普通
str.replace()
函数一次只能查找一个要替换的模式。因此,当您调用msg.replace('\r\n', '')
时,实际上您正在尝试替换所有的实例,其中回车符是后跟一个换行符。而是链接replace命令(请参见答案here):另一种选择是使用regular expressions,它可以一次替换多个模式:
相关问题 更多 >
编程相关推荐