描述
Python len() 方法返回對象(字符串、列表、元組、字典等)長度或項目個數。
語法
len() 方法語法:
len(obj)
參數
- obj -- 對象(字符串、列表、元組、字典等)。
返回值
返回對象長度。
實例
以下幾個實例展示了 len() 方法的使用方法:
1.字符串長度:
>>>S = "runoob" >>> len(S) # 字符串長度 6 >>> l = [1,2,3,4,5] >>> len(l) # 列表元素個數 5
2.列表長度:
#!/usr/bin/python3 list1 = ['Google', 'Runoob', 'Taobao'] print (len(list1)) list2=list(range(5)) # 創建一個 0-4 的列表 print (len(list2))
以上實例輸出結果如下:
3 5
3.元祖長度:
#!/usr/bin/python3
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print("First tuple length : ", len(tuple1))
print( "Second tuple length : ", len(tuple2))
以上實例輸出結果如下:
First tuple length : 3 Second tuple length : 2
4.字典長度:
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7};
print ("Length : %d" % len (dict))
以上實例輸出結果如下:
Length : 2
