当前位置:首页 > 行业动态 > 正文

python里的len函数用法

len函数用于获取Python对象的长度,如字符串、列表、元组等。使用方法为:len(对象)。

len函数是Python内置函数之一,用于获取序列(如字符串、列表、元组等)的长度,下面是关于len函数的详细用法:

1、获取字符串长度:

python里的len函数用法

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

2、获取列表长度:

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

3、获取元组长度:

python里的len函数用法

my_tuple = (10, 20, 30)
length = len(my_tuple)
print(length)  # 输出:3 

4、获取字典键值对数量:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
length = len(my_dict)
print(length)  # 输出:3 

5、获取文件行数:

python里的len函数用法

with open("example.txt", "r") as file:
    lines = file.readlines()
    length = len(lines)
    print(length)  # 输出:文件行数 

len函数可以用于获取各种序列的长度,包括字符串、列表、元组和字典,对于文件,可以使用readlines()方法将文件内容读取为行列表,然后使用len函数获取行数。