Python len() 函式



Python 的 len() 函式 是一個 內建函式,用於確定物件的長度。這裡,物件可以是字串、列表、字典或任何其他可迭代物件。

請注意,len() 僅適用於被視為集合的物件。如果我們將整數或浮點數傳遞給此函式,直譯器將丟擲 TypeError。

語法

以下是 Python len() 函式的語法:

len(object)

引數

Python len() 函式接受單個引數:

返回值

Python len() 函式返回指定物件的長度。

len() 函式示例

練習以下示例以瞭解如何在 Python 中使用 len() 函式

示例:使用 len() 函式計算字串長度

如果我們將字串傳遞給 len() 函式,它將檢索給定字串中的字元數,包括標點符號、空格和所有型別的特殊字元。在下面的程式碼中,我們定義一個字串並嘗試查詢其長度。

definedStr = "Welcome to Tutorials Point"
lengthOfStr = len(definedStr)
print("The length of the given string is:", lengthOfStr)

以下是上述程式碼的輸出:

The length of the given string is: 26

示例:使用 len() 函式計算列表長度

將列表傳遞給 len() 函式會返回該列表中可用專案的數量。以下程式碼演示瞭如何使用 len() 函式從指定列表中獲取元素的總數。

definedList = ["Simply", "Easy", "Learning", "Tutorials", "Point"]
lengthOfList = len(definedList)
print("The length of the given List is:", lengthOfList)

上述程式碼的輸出如下:

The length of the given List is: 5

示例:使用 len() 函式獲取字典長度

由於字典也是一種集合型別,因此 len() 函式也支援它。在下面的程式碼中,我們正在查詢字典的長度。

definedDict = {"OrgName":"Tutorialspoint", "Location":"Hyderabad"}
lengthOfDict = len(definedDict)
print("The length of the given dictionary is:", lengthOfDict)

以下是上述 Python 程式碼的輸出:

The length of the given dictionary is: 2
python_built_in_functions.htm
廣告