Python String splitlines() 方法
Python字符串splitlines()方法用于在行边界分割行。该函数返回字符串中的行数列表,包括换行(可选).
语法:
string.splitlines([keepends])
参数:
keepends (可选) : 当设置为True时,换行将被包含在结果列表中。这可以是一个数字,指定换行的位置,或者可以是任何Unicode字符,如”\n”、”\r”、”\r\n “等作为字符串的边界.
返回值:
返回字符串中的行的列表,在行的边界处断开.
splitlines()在下列行的边界上进行分割:
| Representation | 描述 | 
|---|---|
| \n | 换行 | 
| \r | 回车 | 
| \r\n | 回车 + 换行 | 
| \x1c | 文件分隔符 | 
| \x1d | 组分隔符 | 
| \x1e | 记录分隔符 | 
| \x85 | 下一行 (C1控制代码) | 
| \v or \x0b | 行式表法 | 
| \f or \x0c | 表格 | 
| \u2028 | 行分隔符 | 
| \u2029 | 段落分隔符 | 
示例1
# Python code to illustrate splitlines()
string = "Welcome everyone to\rthe world of Geeks\nGeeksforGeeks"
  
# No parameters has been passed
print (string.splitlines( ))
  
# A specified number is passed
print (string.splitlines(0))
  
# True has been passed 
print (string.splitlines(True))
输出:
['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
['Welcome everyone to\r', 'the world of Geeks\n', 'GeeksforGeeks']
示例2
# Python code to illustrate splitlines()
string = "Cat\nBat\nSat\nMat\nXat\nEat"
  
# No parameters has been passed
print (string.splitlines( ))
  
# splitlines() in one line
print('India\nJapan\nUSA\nUK\nCanada\n'.splitlines())
输出:
['Cat', 'Bat', 'Sat', 'Mat', 'Xat', 'Eat']
['India', 'Japan', 'USA', 'UK', 'Canada']
示例3: Practical Application
在这段代码中,我们将了解如何使用splitlines()的概念来计算一个字符串中每个字的长度.
# Python code to get length of each words
def Cal_len(string):
      
    # Using splitlines() divide into a list
    li = string.splitlines()
    print (li)
      
    # Calculate length of each word
    l = [len(element) for element in li]
    return l
  
# Driver Code    
string = "Welcome\rto\rGeeksforGeeks"
print(Cal_len(string))
输出:
['Welcome', 'to', 'GeeksforGeeks']
[7, 2, 13]
极客教程