len()函数是Python中的库函数,用于获取对象的长度(对象可以是字符串,列表,元组等)。它接受一个对象并返回其长度(如果是字符串,则为字符总数,如果是可迭代的则为元素总数)。
语法:
len(object)
参数: object –一个对象,例如字符串,列表等,其长度将被计算。
返回值: int –返回对象的长度。
示例
Input: a = "Hello world!" print(len(a)) Output: 12
Python代码获取对象的长度(字符串,列表等)
# python代码演示一个例子
# of len() function
a = "Hello world!" # 字符串值
b = [10, 20, 30, 40, 50] # 列表
c = ["Hello", "World!", "Hi", "Friends"] # 列表 of strings
d = ("Hello", "World!", "Hi", "Friends") # 元组
print("length of a: ", len(a))
print("length of b: ", len(b))
print("length of d: ", len(c))
print("length of c: ", len(d))输出结果
length of a: 12 length of b: 5 length of d: 4 length of c: 4