在Python中,`len()`函数用于获取一个对象的长度或元素个数。以下是一些基本用法:
字符串长度
string = "Hello, World!"
length = len(string)
print(length) 输出:13
列表长度
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
字典长度
dict1 = {"name": "John", "age": 25, "city": "New York"}
length = len(dict1)
print(length) 输出:3
整数长度(会引发`TypeError`异常):
number = 12345
length = len(number) TypeError: object of type 'int' has no len()
`len()`函数不能直接用于非序列类型的对象,如整数、浮点数等。如果尝试这样做,会引发`TypeError`异常。
需要注意的是,`len()`函数是Python的内置函数,因此不需要导入任何模块即可使用