Python中的len函数如何用
时间: 2024-04-29 21:03:37 浏览: 14
len函数用于获取一个序列(字符串、列表、元组等)的长度,返回值为整数。可以像下面这样使用:
```python
# 字符串
s = "Hello, World!"
print(len(s)) # 输出:13
# 列表
lst = [1, 2, 3, 4, 5]
print(len(lst)) # 输出:5
# 元组
tup = (1, 2, 3)
print(len(tup)) # 输出:3
```
也可以用于自定义对象,只需要实现`__len__`方法即可。例如:
```python
class MyList:
def __init__(self, lst):
self.lst = lst
def __len__(self):
return len(self.lst)
my_lst = MyList([1, 2, 3, 4, 5])
print(len(my_lst)) # 输出:5
```
相关问题
python 中len函数
len函数是Python内置的一个函数,用于返回一个对象的长度或元素个数。它可以用于字符串、列表、元组、字典、集合等可迭代对象。
例如,我们可以使用len函数来获取字符串的长度:
```python
my_string = "Hello, World!"
print(len(my_string))
```
输出结果为:13
同样,我们也可以使用len函数来获取列表的元素个数:
```python
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
```
输出结果为:5
总之,len函数是一个非常有用的函数,可以帮助我们获取对象的长度或元素个数。
python中len函数
len函数在Python中用于获取一个序列(字符串、列表、元组等)的长度或者元素个数。它的语法格式为:len(sequence),其中sequence是需要获取长度的序列。
例如,如果我们要获取一个字符串s的长度,可以使用以下代码:
```
s = "Hello, World!"
print(len(s)) # 输出结果为13
```
同样,如果我们要获取一个列表lst的长度,可以使用以下代码:
```
lst = [1, 2, 3, 4, 5]
print(len(lst)) # 输出结果为5
```
总之,len函数是一个非常常用的函数,可以帮助我们快速获取序列的长度或者元素个数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)