📜  Python String splitlines() 方法

📅  最后修改于: 2022-05-13 01:54:48.548000             🧑  作者: Mango

Python String splitlines() 方法

Python String splitlines()方法用于在行边界处拆分行。该函数返回字符串中的行列表,包括换行符(可选)。

splitlines() 在以下行边界上拆分:

Representation

Description

\nLine Feed
\rCarriage Return
\r\nCarriage Return + Line Feed
\x1cFile Separator
\x1dGroup Separator
\x1eRecord Separator
\x85Next Line (C1 Control Code)
\v or \x0bLine Tabulation
\f or \x0cForm Feed
\u2028Line Separator
\u2029Paragraph Separator

示例 1

Python3
# 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))


Python3
# 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())


Python3
# 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 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

Python3

# 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:实际应用

在这段代码中,我们将了解如何使用 splitlines() 的概念来计算字符串中每个单词的长度。

Python3

# 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]