【问题标题】:Newline within list not printing on separate line列表中的换行符不在单独的行上打印
【发布时间】:2016-12-20 19:06:15
【问题描述】:

我采用 unicode 文本数据类型,然后通过正则表达式对其进行解析以查找信息并将其附加到列表中。此列表中的数据可以非常但有一个已知对象,我总是想在单独的行上开始。此时我尝试在我的列表中添加一个换行符,它总是在正确的位置添加换行符,但似乎这个字符在打印时只是被视为列表中的一个对象,而不是实际强制输出打印在单独的行上。有人对我如何将这些数据强制到另一行有任何建议吗?

=============== 当前程序输出全部在同一行 ==============

['\n', u'10.41.71.19 ', u'64512', '\n', u'192.168.0.1 ']

=============== 两行的期望输出 ==============

[u'10.41.71.19 ', u'64512', 

u'192.168.0.1 ']

============= 带有代码的片段,我在我的列表中添加新行 ======

def jnprBgp(output):

 for line in output.splitlines():
    peerip = re.search('(\d+.\d+.\d+.\d+.)', line)
    if peerip:
       testlist.append('\n')
       testlist.append(peerip.groups()[0])
    peeras = re.search('\d+.\d+.\d+.\d+.\s+(\d+)', line)
    if peeras:
       testlist.append(peeras.groups()[0])

 for line in testlist:
    print testlist

【问题讨论】:

    标签: python list printing newline line-breaks


    【解决方案1】:

    打印带有字符串'\n' 作为元素的列表不会导致打印实际的换行符。这意味着您应该自己处理列表的打印,如下所示:

    def printList(l):
        print '[%s]' % ', '.join([repr(elem) if elem != '\n' else '\n' for elem in l])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 2013-04-05
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      相关资源
      最近更新 更多