【问题标题】:Getting rid of new line and carriage return characters in python摆脱python中的换行符和回车符
【发布时间】:2020-09-09 09:11:20
【问题描述】:

我正在创建一个网络应用程序,并且我正在使用 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 python-3.x string methods replace


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 2015-09-28
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      相关资源
      最近更新 更多