在python中去掉新行和回车符

2024-05-19 07:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个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

Tags: 字符串fromweb应用程序on电子邮件msg字符
1条回答
网友
1楼 · 发布于 2024-05-19 07:41:22

Python的普通str.replace()函数一次只能查找一个要替换的模式。因此,当您调用msg.replace('\r\n', '')时,实际上您正在尝试替换所有的实例,其中回车符是后跟一个换行符。而是链接replace命令(请参见答案here):

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

另一种选择是使用regular expressions,它可以一次替换多个模式:

import re
msg2 = re.sub(r'\r\n', ' ', my_email)

相关问题 更多 >

    热门问题