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')
Official Documentation: partition()
官方文档: partition()
翻译自: https://www.journaldev.com/24420/python-string-partition-rpartition
partition拼字符串