Python 字符串 splitlines()方法
Python splitlines() 方法根据行拆分字符串。它在行边界处打断字符串,并返回一个拆分后的字符串列表。换行符可以是新行(\n)、回车(\r)等。下表列出了拆分字符串的行分隔符。
该方法根据给定的行边界进行拆分。
表示 | 描述 |
---|---|
\n | 换行符 |
\r | 回车符 |
\r\n | 回车符加换行符 |
\v 或 \x0b | 线制表符 |
\f 或 \x0c | 换页符 |
\x1c | 文件分隔符 |
\x1d | 组分隔符 |
\x1e | 记录分隔符 |
\x85 | 换行字符(C1控制码) |
\u2028 | 行分隔符 |
\u2029 | 段落分隔符 |
语法
splitlines([keepends])
参数
keepends : 它是一个布尔值,可以是True或False。可选的。
返回值
它返回一个以逗号分隔的行列表。
让我们看一些splitlines()方法的示例来理解它的功能。
示例1
# Python splitlines() method example
# Variable declaration
str = "Java is a programming language"
# Calling function
str2 = str.splitlines() # returns a list having single element
print(str)
print(str2)
str = "Java \n is a programming \r language"
str2 = str.splitlines() # returns a list having splitted elements
print(str2)
输出:
Java is a programming language
['Java is a programming language']
['Java ', ' is a programming ', ' language']
示例2
将True传递给该方法,将导致包含换行符到字符串列表中。请参阅下面的示例。
# Python splitlines() method example
# Variable declaration
str = "Java \n is a programming \r language"
# Calling function
str2 = str.splitlines(True) # returns a list having splitted elements
print(str2)
输出:
['Java \n', ' is a programming \r', ' language']
示例3
# Python splitlines() method example
# Variable declaration
str = "Java \n is a programming \r language for \r\n software development"
# Calling function
str2 = str.splitlines() # returns a list having splitted elements
# Displaying result
print(str2)
# getting back list to string
print("".join(str2)) # now it does not contain any line breaker character
输出:
['Java ', ' is a programming ', ' language for ', ' software development']
Java is a programming language for software development