# 示例代码:使用 len 函数计算字符串、列表、元组等的长度
# 计算字符串的长度
string = "Hello, world!"
length_of_string = len(string)
print(f"字符串 '{string}' 的长度是: {length_of_string}") # 输出: 字符串 'Hello, world!' 的长度是: 13
# 计算列表的长度
list_example = [1, 2, 3, 4, 5]
length_of_list = len(list_example)
print(f"列表 {list_example} 的长度是: {length_of_list}") # 输出: 列表 [1, 2, 3, 4, 5] 的长度是: 5
# 计算元组的长度
tuple_example = (10, 20, 30, 40, 50)
length_of_tuple = len(tuple_example)
print(f"元组 {tuple_example} 的长度是: {length_of_tuple}") # 输出: 元组 (10, 20, 30, 40, 50) 的长度是: 5
# 计算字典的长度(返回键的数量)
dict_example = {'a': 1, 'b': 2, 'c': 3}
length_of_dict = len(dict_example)
print(f"字典 {dict_example} 的长度是: {length_of_dict}") # 输出: 字典 {'a': 1, 'b': 2, 'c': 3} 的长度是: 3
len()
是 Python 内置函数,用于返回对象的长度或元素个数。len()
返回字符的数量;对于列表和元组,返回元素的数量;对于字典,返回键的数量。上一篇:python ord和chr
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站