温馨提示×

python中len()函数的用法是什么

小亿
81
2024-09-13 14:36:19
栏目: 编程语言

len() 是 Python 的一个内置函数,用于返回对象(如字符串、列表、元组等)的长度或项目数。这个函数只接受一个参数,即你想要计算长度的对象。

以下是 len() 函数的一些基本用法:

  1. 计算字符串的长度:
text = "Hello, world!"
length = len(text)
print(length)  # 输出:13
  1. 计算列表的长度:
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)  # 输出:5
  1. 计算元组的长度:
my_tuple = (6, 7, 8, 9)
length = len(my_tuple)
print(length)  # 输出:4

注意,len() 函数不能直接计算整数、浮点数或其他非序列类型的对象的长度。在这种情况下,你会收到一个 TypeError。

例如:

number = 12345
length = len(number)  # 这将引发一个错误

0