Tutorial Study Image

Python splitlines()

Python 中的 splitlines() 函数有助于返回字符串中的行列表,其中分割是根据换行符进行的。它接受一个布尔值作为其参数。


str.splitlines([keepends]) #where keepends is a boolean value
 

splitlines() 参数

splitlines() 函数接受一个参数。默认情况下,不提供换行符。换行符也包含在列表项中,它可以是以下任何一种。

\n 换行符 (Line Feed)
\r 回车符 (Carriage Return)
\r\n 回车符 + 换行符 (Carriage Return + Line Feed)
\v\x0b 垂直制表符 (Line Tabulation)
\f\x0c 换页符 (Form Feed)
\x1c 文件分隔符 (File Separator)
\x1d 组分隔符 (Group Separator)
\x1e 记录分隔符 (Record Separator)
\x85 下一行 (C1 控制代码)
\u2028 行分隔符 (Line Separator)
\u2029 段落分隔符 (Paragraph Separator)

 

参数 描述 必需/可选
keepends 指定是否包含换行符(True),或不包含(False) 可选

splitlines() 返回值

如果未给出换行符,它将返回一个包含单个项目(单行)的列表。

输入 返回值
如果 keepends 为 True 字符串中的行列表

 

Python 中 splitlines() 方法的示例

示例 1:splitlines() 在 Python 中如何工作?


fruits = 'Apple\Orange\r\nBanana\rGrapes'

print(fruits .splitlines())
print(fruits .splitlines(True))

fruits = 'Apple Orange Banana Grapes'
print(fruits.splitlines())
 

输出


['Apple', 'Orange', 'Banana', 'Grapes']
['Apple\n', 'Orange\r\n', 'Banana\r', 'Grapes']
['Apple Orange Banana Grapes']

示例 2:splitlines() 在 Python 中的应用


string = "Hi How are you\nIam fine.."

output = string.splitlines(True)

print(output)
 

输出


['Hi How are you\n', 'Iam fine..']