在Python中,`len()`函数用于获取一个对象的长度或元素个数。以下是一些基本用法:
字符串长度:
```python
string = "Hello World"
length = len(string)
print(length) 输出:11
列表长度:```pythonlist1 = [1, 2, 3, 4, 5]
length = len(list1)
print(length) 输出:5
元组长度:
```python
tuple1 = (1, 2, 3, 4, 5)
length = len(tuple1)
print(length) 输出:5
集合长度:```pythonset1 = {1, 2, 3, 4, 5}
length = len(set1)
print(length) 输出:5
字典长度:
```python
dict1 = {"name": "John", "age": 25, "city": "New York"}
length = len(dict1)
print(length) 输出:3
判断对象是否为空:```pythonif len(list) == 0:
print("列表为空")
`len()`函数也可以用于获取字节数,例如:
```python
str = "信春哥,得永生"
print(len(str.encode())) 输出:14
请注意,`len()`函数仅适用于那些具有长度的对象,如字符串、列表、元组、集合和字典。对于其他类型的对象,`len()`函数可能会引发`TypeError`异常。

