欢迎访问宙启技术站
智能推送

使用Python中的len函数计算字符串、列表等数据类型的长度?

发布时间:2023-06-29 22:19:54

在Python中,len()函数是用来计算字符串、列表、元组等数据类型的长度的。

1. 字符串长度计算示例:

string = "Hello, World!"
length = len(string)
print(length)  # 输出 13

2. 列表长度计算示例:

list = [1, 2, 3, 4, 5]
length = len(list)
print(length)  # 输出 5

3. 元组长度计算示例:

tuple = (1, 2, 3, 4, 5)
length = len(tuple)
print(length)  # 输出 5

4. 字典长度计算示例:

dictionary = {"a": 1, "b": 2, "c": 3}
length = len(dictionary)
print(length)  # 输出 3

5. 集合长度计算示例:

set = {1, 2, 3, 4, 5}
length = len(set)
print(length)  # 输出 5

总结来说,len()函数可以计算字符串、列表、元组、字典、集合等数据类型的长度。无论是字符个数还是元素个数,len()函数都可以正确计算。