Python 的 str.partition(~)
方法在第一次出現分隔符時拆分字符串,以返回包含三個元素的元組:分隔符之前的部分、分隔符本身以及分隔符之後的部分。
參數
1. sep
| string
用作分隔符的字符串。
返回值
返回值取決於以下情況:
案子 |
返回值 |
---|---|
在字符串中找到分隔符 |
具有三個元素的元組: 第一個元素:分隔符之前的部分 第二個元素:分隔符本身 第三個元素:分隔符之後的部分 |
在字符串中找不到分隔符 |
具有三個元素的元組: 第一個元素:字符串本身 第二個元素:空字符串 第三個元素:空字符串 |
例子
在字符串中找到分隔符
要在第一次出現 'll'
時拆分字符串 "Hello fellow SkyTowner!"
:
x = "Hello fellow SkyTowner!"
x.partition('ll')
('He', 'll', 'o fellow SkyTowner!')
('He', 'll', 'o fellow SkyTowner!')
請注意,我們返回一個元組,其中包含分隔符之前的部分 ( 'He'
)、分隔符本身 ( 'll'
) 以及分隔符之後的部分 ( 'o fellow SkyTowner!'
)。
在字符串中找不到分隔符
要在第一次出現 'tt'
時拆分字符串 "Hello fellow SkyTowner!"
:
y = "Hello fellow SkyTowner!"
y.partition('tt')
('Hello fellow SkyTowner!', '', '')
由於在字符串 "Hello fellow SkyTowner!"
中找不到分隔符 'tt'
,因此我們返回一個包含原始字符串和兩個空字符串的元組。
相關用法
- Python String partition()用法及代碼示例
- Python String count方法用法及代碼示例
- Python String isnumeric方法用法及代碼示例
- Python String Center()用法及代碼示例
- Python String zfill方法用法及代碼示例
- Python String rstrip方法用法及代碼示例
- Python String decode()用法及代碼示例
- Python String count()用法及代碼示例
- Python String join()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String isalnum()用法及代碼示例
- Python String endswith方法用法及代碼示例
- Python String rsplit()用法及代碼示例
- Python String isidentifier()用法及代碼示例
- Python String startswith()用法及代碼示例
- Python String rjust方法用法及代碼示例
- Python String rpartition()用法及代碼示例
- Python String rpartition方法用法及代碼示例
- Python String ljust方法用法及代碼示例
- Python String splitlines()用法及代碼示例
- Python String upper()用法及代碼示例
- Python String isprintable()用法及代碼示例
- Python String split方法用法及代碼示例
- Python String splitlines方法用法及代碼示例
- Python String strip方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python String | partition method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。