Python String splitlines() 方法用於分割線邊界處的線。該函數返回字符串中的行列表,包括換行符(可選)。
用法:
string.splitlines([保持])
參數:
keepends(可選):當設置為 True 時,結果列表中包含換行符。這可以是一個數字,指定換行符的位置,也可以是任何 Unicode 字符,如 “\n”、“\r”、“\r\n” 等作為字符串的邊界。
返回值:
返回字符串中的行列表,在行邊界處斷開。
splitlines() 在以下線邊界上拆分: Representation Description\ n 換行 \ r 回車 \ r \ n 回車+換行 \ x1c 文件分隔符 \ x1d 組分隔符 \ x1e 記錄分隔符 \ x85 下一行(C1控製碼) \v 或 \x0b 線製表 \f 或 \x0c 換頁 \ u2028 分線器 \ u2029 段落分隔符
例子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))
輸出:
['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]
相關用法
- Python String casefold()用法及代碼示例
- Python String center()用法及代碼示例
- Python String count()用法及代碼示例
- Python String endswith()用法及代碼示例
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Python String splitlines() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。