>>> s = 'this is a delicious apple pie'
>>> pre, target, post = s.partition('delicious')
>>> pre
'this is a '
>>> target
'delicious'
>>> post
' apple pie'
如果目标子字符串未包含在完整字符串中,则返回的元组在第2和第3个位置将有空字符串:
>>> s2 = 'this is an apple pie'
>>> s2.partition('delicious')
('this is an apple pie', '', '')
如果您确定该变量包含“delicious”的一次出现,您可以使用
split
:但如果变量不包含单词,则必须防止可能的
IndexError
!你知道吗字符串对象包含一个方法^{} ,它正是为这种用途而设计的。你知道吗
如果目标子字符串未包含在完整字符串中,则返回的元组在第2和第3个位置将有空字符串:
在正则表达式中使用正向查找:
Demo on Regex101。你知道吗
相关问题 更多 >
编程相关推荐