當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python len()用法及代碼示例

Python len() 函數

len() 函數是 Python 中的一個庫函數,用於獲取對象的長度(對象可以是字符串、列表、元組等)。它接受一個對象並返回其長度(字符串情況下的字符總數,可迭代情況下的元素總數)。

用法:

    len(object)

參數:object– 要計算長度的對象,如字符串、列表等。

返回值: int– 返回對象的長度。

例:

    Input:
    a = "Hello world!"
    print(len(a))
    
    Output:
    12

獲取對象長度的 Python 代碼(字符串、列表等)

# python code to demonstrate an example
# of len() function

a = "Hello world!"          # string value
b = [10, 20, 30, 40, 50]    # list
c = ["Hello", "World!", "Hi", "Friends"] # list of strings
d = ("Hello", "World!", "Hi", "Friends") # Tuple

print("length of a:", len(a))
print("length of b:", len(b))
print("length of d:", len(c))
print("length of c:", len(d))

輸出

length of a: 12
length of b: 5
length of d: 4
length of c: 4


相關用法


注:本文由純淨天空篩選整理自 len() function with example in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。