python中splitlines的用法_Python string splitlines()用法及代码示例

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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值