当前位置:首页 > 行业动态 > 正文

python中的len函数的用法

Python中的len函数用于获取对象(字符串、列表、元组等)的长度,返回一个整数。len(“hello”) 返回5。

在Python中,len()函数用于返回对象(字符、列表、元组等)的长度,以下是一些使用len()函数的例子:

python中的len函数的用法  第1张

1. 计算字符串长度

str = "Hello, World!"
print(len(str))

输出结果为:

示例代码 输出结果
str = "Hello, World!" 13

2. 计算列表长度

list = [1, 2, 3, 4, 5]
print(len(list))

输出结果为:

示例代码 输出结果
list = [1, 2, 3, 4, 5] 5

3. 计算元组长度

tuple = (1, 2, 3, 4, 5)
print(len(tuple))

输出结果为:

示例代码 输出结果
tuple = (1, 2, 3, 4, 5) 5
0