簡體   English   中英

字符串格式與列表和元組的區別

[英]String formatting difference with list and tuple

以下語句有什么區別:

exam_st_date = (11,12,2014)

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

當我執行此 python 語句時,我得到 output:考試將從:11 / 12 / 2014 開始

但是如果我將exam_st_date = (11,12,2014) 更改為

exam_st_date = [11,12,2014] 

作為列表格式

如果我再次執行相同的語句然后我得到錯誤

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

你得到一個 TypeError。 這意味着您傳遞給您的打印 function 的變量不是所需的類型。 您被要求傳遞 integer 而不是列表。 Python 將您創建的列表視為一個 object 而不是 3 個整數。

在您的工作示例中,您使用的是一個元組,它被識別為 3 個 integer 變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM