📜  Python String partition() 方法

📅  最后修改于: 2022-05-13 01:54:20.006000             🧑  作者: Mango

Python String partition() 方法

Python String partition() 方法在第一次出现分隔符时拆分字符串,并返回一个元组,其中包含分隔符之前的部分、分隔符和分隔符之后的部分。这里的分隔符是一个作为参数给出的字符串。

示例 1

Python3
string = "pawan is a good"
  
# 'is' separator is found
print(string.partition('is '))
  
# 'not' separator is not found
print(string.partition('bad '))
  
string = "pawan is a good, isn't it"
  
# splits at first occurrence of 'is'
print(string.partition('is'))


Python3
string = "geeks is a good"
  
# 'is' separator is found
print(string.partition('is '))
  
# 'not' separator is not found
print(string.partition('bad '))
  
string = "geeks is a good, isn't it"
  
# splits at first occurrence of 'is'
print(string.partition('is'))


输出:

('pawan ', 'is ', 'a good')
('pawan is a good', '', '')
('pawan ', 'is', " a good, isn't it")

示例 2

Python3

string = "geeks is a good"
  
# 'is' separator is found
print(string.partition('is '))
  
# 'not' separator is not found
print(string.partition('bad '))
  
string = "geeks is a good, isn't it"
  
# splits at first occurrence of 'is'
print(string.partition('is'))

输出:

('geeks ', 'is ', 'a good')
('geeks is a good', '', '')
('geeks ', 'is', " a good, isn't it")