partition拼字符串_Python字符串partition(),rpartition()

partition拼字符串

Python String partition() function splits a string based on a separator into a tuple with three strings. The first string is the part before the separator, the second string is the separator and the third string is the part after the separator.

Python String partition()函数将基于分隔符的字符串拆分为具有三个字符串的元组 。 第一个字符串是分隔符之前的部分,第二个字符串是分隔符,第三个字符串是分隔符之后的部分。

Python字符串partition() (Python String partition())

This function syntax is:

该函数语法为:

str.partition(sep)

If the separator string is not found, then the 3-tuple contains the string itself followed by two empty strings.

如果找不到分隔符字符串,则三元组包含字符串本身,后跟两个空字符串。

Let’s look at some examples of partition() function.

让我们看一下partition()函数的一些示例。

s = 'Hello World 2019'

parts_tuple = s.partition('World')
print(parts_tuple)

parts_tuple = s.partition('2018')
print(parts_tuple)

Output:

输出:

('Hello ', 'World', ' 2019')
('Hello World 2019', '', '')

Python字符串rpartition() (Python String rpartition())

Python String rpartition() splits the string at the last occurrence of the separator string. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

Python字符串rpartition()在最后一次出现分隔符字符串时拆分字符串。 如果找不到分隔符,则返回一个包含两个空字符串的三元组,然后是字符串本身。

s = 'Hello World 2019'

parts_tuple = s.rpartition('World')
print(parts_tuple)

parts_tuple = s.rpartition('2018')
print(parts_tuple)

Output:

输出:

('Hello ', 'World', ' 2019')
('', '', 'Hello World 2019')

Let’s look at an example where the difference between partition() and rpartition() function will be clear.

让我们看一个例子,其中partition()和rpartition()函数之间的区别将很明显。

s = 'ABCBA'
parts_tuple = s.partition('B')
print(parts_tuple)

parts_tuple = s.rpartition('B')
print(parts_tuple)

Output:

输出:

('A', 'B', 'CBA')
('ABC', 'B', 'A')
GitHub Repository. GitHub存储库中签出更多Python示例。

Official Documentation: partition()

官方文档: partition()

翻译自: https://www.journaldev.com/24420/python-string-partition-rpartition

partition拼字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值