python解析字符串\ r \ n新行

时间:2014-05-15 10:59:51

标签: python parsing eval

我在分析行时遇到一些问题。 实际上我在这一行中拥有一切:

'test:[abc:123];something\r\nName=some name;phone no.: [123456]\r\nAddress: some address; another   address\r\n\r\n'

我希望这条线像这样:

test:[abc:123];something
Name=some name;phone no.: [123456]
Address: some address; another address

我试过

#from ast import literal_eval
from ast import *
a = 'test:[abc:123];something\r\nName=some name;phone no.: [123456]\r\nAddress: some address; another address\r\n\r\n'
msg = literal_eval(a)
# and
msg = eval(a)

但我得到错误。有没有其他简单的方法来解决这个问题?

3 个答案:

答案 0 :(得分:5)

kk = 'test:[abc:123];something\r\nName=some name;phone no.: [123456]\r\nAddress: some address; another address\r\n\r\n'
lk = "\n".join(kk.split("\r\n"))
print lk 

<强>输出:

test:[abc:123];something
Name=some name;phone no.: [123456]
Address: some address; another   address

答案 1 :(得分:1)

如果这是您生成的字符串,请尝试.splitlines()

.split('\r\n')?

如果从文件中读取此内容,请在打开文件时尝试设置行结尾。 或者使用myfile = open(filename, 'r', newline='\n\r')

打开文件

答案 2 :(得分:0)

拆分工作正常:

    l = 'test:[abc:123];something\r\nName=some name;phone no.: [123456]\r\nAddress: some address; another   address\r\n\r\n'.split("\r\n")
    In [14]: for line in l:
   ....:         print line
   ....:     
    test:[abc:123];something
    Name=some name;phone no.: [123456]
    Address: some address; another   address