splitline()方法用於在線邊界處分割線。該函數返回字符串中的行列表,包括換行符(可選)。
用法:
string.splitlines([keepends])
參數:
- keepends (可選):當設置為True時,結果列表中將包含換行符。
- 這可以是一個數字,指定換行的位置,也可以是任何Unicode字符,例如“\n”,“\r”,“\r\n”等作為字符串的邊界。
返回值:
Returns a list of the lines in the string, breaking at line boundaries.
下麵的代碼顯示了splitline()方法的圖示。代碼#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']
實際應用:
在這段代碼中,我們將了解如何使用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]
相關用法
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Python String | splitlines()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。