python如何取行数

原创
ithorizon 7个月前 (09-28) 阅读数 65 #Python

Python中有很多方法可以用来获取行数,其中一种是使用内置函数len(),另一种是使用fileinput模块。

方法一:使用len()函数

Python中,len()函数可以返回任何数据类型的长度,包括字符串、列表、元组和字典等,如果要获取一个字符串的行数,可以将字符串拆分成行,然后返回行的数量。

以下是一个示例代码:

string = "This is the first line.\nThis is the second line."
lines = string.split("\n")
num_lines = len(lines)
print("The string has", num_lines, "lines.")

方法二:使用fileinput模块

fileinput模块可以用来逐行读取文件,如果要获取一个文件的行数,可以使用fileinput模块逐行读取文件,然后计数。

以下是一个示例代码:

import fileinput
lines = fileinput.input()
num_lines = 0
for line in lines:
    num_lines += 1
print("The file has", num_lines, "lines.")

无论使用哪种方法,都可以获取Python中字符串或文件的行数。



热门