len函数用于获取xwenw.com/tag/python" target="_blank">Python对象的长度,如字符串、列表、元组等。使用方法为:len(对象)。

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

1、获取字符串长度:

python里的len函数用法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函数用法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函数用法python里的len函数用法

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

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。