Python打印带有换行符的数组

38

我是 Python 的新手,有一个简单的数组:

op = ['Hello', 'Good Morning', 'Good Evening', 'Good Night', 'Bye']

当我使用pprint时,我得到了以下输出:

['Hello', 'Good Morning', 'Good Evening', 'Good Night', 'Bye']

有没有办法去掉引号、逗号和括号,并将它们打印在单独的一行上。这样输出就是这样的:


Is there anyway i can remove the quotes, commas and brackets and print on a seperate line. So that the output is like this:
Hello
Good Morning
Good Evening
Good Night
Bye
5个回答

50

你可以使用换行符将字符串join起来,然后打印出结果字符串:

print "\n".join(op)

44

11

以下是一些澄清点:

  1. 首先,你手上的是一个列表(list),而不是一个数组(array)。两者的区别在于,列表是一种更为动态和灵活的数据结构(至少在像Python这样的动态语言中是这样的)。例如,你可以有多个不同类型的对象(例如2个字符串、3个整数、1个套接字等)。

  2. 列表中单词周围的引号表示它们是字符串类型的对象。

  3. 当你执行 print op(或者在Python 3+中执行 print(op))时,你实际上是在请求Python显示该特定列表对象及其内容的可打印表示形式。因此有引号、逗号、括号等。

  4. 在Python中,你可以使用非常简单的 for each 循环来迭代可迭代对象(例如一个列表)。只需要这样做:

  5. for greeting in op: 
         print greeting
    

6

逐行打印

for word in op:
    print word

这种方法的优点是,如果op非常长,那么您不必仅出于打印目的而创建一个新的临时字符串。


1

你也可以使用Pretty Printpprint来获得更好的打印效果。

Pretty Print会在超过一定阈值时自动换行,因此如果你只有少量短项目,它会显示为内联:

from pprint import pprint
xs = ['Hello', 'Morning', 'Evening']
pprint(xs)
# ['Hello', 'Morning', 'Evening']

但如果你有很多内容,它会自动换行:

from pprint import pprint
xs = ['Hello', 'Good Morning', 'Good Evening', 'Good Night', 'Bye', 'Aloha', 'So Long']
pprint(xs)
# ['Hello',
#  'Good Morning',
#  'Good Evening',
#  'Good Night',
#  'Bye',
#  'Aloha',
#  'So Long']

你也可以使用参数 width= 来指定列宽。

参见: 如何在Python中“漂亮地”打印列表


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接