如何使用Python中的len函数获取序列对象的长度
发布时间:2023-06-18 23:02:12
在Python中,len函数被用于获取序列对象的长度。序列对象可以是任何一种对象,如字符串、列表、元组和字典等。
len函数的语法如下:
len(object)
其中,object是需要获取长度的序列对象。
使用len函数获取序列对象的长度非常简单,只需要将需要获取长度的序列对象作为参数传递给len函数即可。例如,下面的代码演示了如何获取一个字符串的长度:
str = "Hello world"
length = len(str)
print("The length of the string is:", length)
输出为:
The length of the string is: 11
同样的,我们也可以获取列表、元组和字典等序列对象的长度。例如,下面的代码演示了如何获取一个列表的长度:
list = [1, 2, 3, 4, 5]
length = len(list)
print("The length of the list is:", length)
输出为:
The length of the list is: 5
需要注意的是,在使用len函数获取字典对象的长度时,len函数返回的是字典中键值对的数量。例如:
dict = {'name': 'Tom', 'age': 18, 'gender': 'M'}
length = len(dict)
print("The length of the dictionary is:", length)
输出为:
The length of the dictionary is: 3
总结来说,使用len函数获取序列对象的长度非常简单,只需要将需要获取长度的序列对象作为参数传递给len函数即可。而不管是获取字符串、列表、元组还是字典的长度,都可以使用len函数来实现。
