📅  最后修改于: 2020-10-30 06:39:46             🧑  作者: Mango
Python splitlines()方法根据行拆分字符串。它在行边界处中断字符串,并返回分割后的字符串列表。换行符可以是新行(\ n),回车符(\ r)等。下面给出了换行符表,该表将字符串拆分。
此方法在给定的线边界上分割。
Representation | Description |
---|---|
\n | Line Feed |
\r | Carriage Return |
\r\n | Carriage Return + Line Feed |
\v or \x0b | Line Tabulation |
\f or \x0c | Form Feed |
\x1c | File Separator |
\x1d | Group Separator |
\x1e | Record Separator |
\x85 | Next Line (C1 Control Code) |
\u2028 | Line Separator |
\u2029 | Paragraph Separator |
splitlines([keepends])
keepends:这是一个布尔值,可以为True或False。它是可选的。
它返回逗号分隔的行列表。
让我们看一些splitlines()方法的例子来了解它的功能。
# 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']
将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']
# 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