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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。