温馨提示×

python的len函数怎么使用

小亿
269
2023-08-11 04:06:17
栏目: 编程语言

len函数用于获取一个对象的长度或元素个数。它的使用方法如下:

  1. 对于字符串,可以使用len函数获取字符串的长度。
string = "Hello World"
length = len(string)
print(length)  # 输出:11
  1. 对于列表、元组、集合等可迭代对象,可以使用len函数获取其中元素的个数。
list1 = [1, 2, 3, 4, 5]
length = len(list1)
print(length)  # 输出:5
tuple1 = (1, 2, 3, 4, 5)
length = len(tuple1)
print(length)  # 输出:5
set1 = {1, 2, 3, 4, 5}
length = len(set1)
print(length)  # 输出:5
  1. 对于字典,可以使用len函数获取其中键值对的个数。
dict1 = {"name": "John", "age": 25, "city": "New York"}
length = len(dict1)
print(length)  # 输出:3
  1. 对于其他对象,len函数可能会返回其他含义的值或引发TypeError异常,具体取决于对象的实现。
number = 12345
length = len(number)
print(length)  # TypeError: object of type 'int' has no len()

总之,len函数可以用于获取字符串、列表、元组、集合、字典等对象的长度或元素个数。

0