简体   繁体   English

字符串格式与列表和元组的区别

[英]String formatting difference with list and tuple

What is the difference in below statements:以下语句有什么区别:

exam_st_date = (11,12,2014)

print( "The examination will start from : %i / %i / %i"%exam_st_date)

When i execute this python statement i get output: The examination will start from: 11 / 12 / 2014当我执行此 python 语句时,我得到 output:考试将从:11 / 12 / 2014 开始

But if i change exam_st_date = (11,12,2014) to但是如果我将exam_st_date = (11,12,2014) 更改为

exam_st_date = [11,12,2014] 

as a list format作为列表格式

and if i execute same statement again then i gets error如果我再次执行相同的语句然后我得到错误

C:\Users\bambored>python C:\Python\examdate.py
Traceback (most recent call last):
  File "C:\Python\examdate.py", line 6, in <module>
    print('The examination will start from : %i / %i / %i'%exam_st_date)
TypeError: %i format: a number is required, not list

you are getting a TypeError.你得到一个 TypeError。 It means that the variable you are passing to your print function is not of the required type.这意味着您传递给您的打印 function 的变量不是所需的类型。 You are asked to pass an integer and not a list.您被要求传递 integer 而不是列表。 Python is treating the list you created as one single object and not as 3 integers. Python 将您创建的列表视为一个 object 而不是 3 个整数。

In your working example, you are using a tuple, which is recognized as 3 integer variables.在您的工作示例中,您使用的是一个元组,它被识别为 3 个 integer 变量。

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

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