简体   繁体   English

在python中打印混合列表

[英]Printing mixed list in python

I am using Python 3.6. 我正在使用Python 3.6。 I am using Learn Python the hard way as reference. 我正在以很难的方式使用Learn Python作为参考。

I have a mixed list and I am trying to print the elements. 我有一个混合列表,我正在尝试打印元素。 The books says to use 书说要用

format code "r" since we don't know what's in the list. 格式代码“ r”,因为我们不知道列表中的内容。 But I am getting error with this. 但是我对此有误。

Was this working in previous versions? 这在以前的版本中有效吗? How can I print mixed list, each element a time. 如何打印混合列表,每个元素一次。

Here is my code and error: 这是我的代码和错误:

change = [1,'pennies',2,'dimes',3,'quarters']
for i in change:
print("I got {:r}".format(i))

Error Stack trace: 错误堆栈跟踪:

Traceback (most recent call last):
  File "<pyshell#52>", line 2, in <module>
    print("I got {:r}".format(i))
ValueError: Unknown format code 'r' for object of type 'int'

Thanks 谢谢

For str.format , the "force to repr " conversion is done with !r . 对于str.format ,将“强制repr ”的转换与完成!r not :r ; 不是:r ; it's not asserting a type for conversion, it's saying "don't use __format__ at all, use __repr__ to perform the conversion". 它不是在声明转换类型,而是在说“根本不要使用__format__ ,请使用__repr__进行转换”。 Make it: 做了:

print("I got {!r}".format(i))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM