Python 的 str.join(~)
方法連接可迭代的元素並返回結果字符串。
參數
1. iterable
| iterable
其元素要連接的可迭代對象。
返回值
可迭代元素的串聯字符串。
例子
基本用法
使用逗號分隔符連接可迭代 x
的元素:
x = ('a', 'b', 'c')
separator = ','
separator.join(x)
'a,b,c'
請注意,元組 x
中的元素在每個項目之間使用分隔符 ','
連接起來。
TypeError
使用逗號分隔符連接可迭代 x
的元素:
x = {1, 2, 3}
separator = ','
print(separator.join(x))
TypeError: sequence item 0: expected str instance, int found
由於可迭代的 x
中存在非字符串值,因此引發 TypeError
。
與詞典一起使用
join(~)
方法將連接字典的鍵而不是值:
cars = {"Ferrari": "red", "Porsche": "silver", "Bentley": "black"}
separator = " > "
separator.join(cars)
'Ferrari > Porsche > Bentley'
相關用法
- Python String join()用法及代碼示例
- Python String count方法用法及代碼示例
- Python String isnumeric方法用法及代碼示例
- Python String Center()用法及代碼示例
- Python String zfill方法用法及代碼示例
- Python String rstrip方法用法及代碼示例
- Python String decode()用法及代碼示例
- Python String count()用法及代碼示例
- 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方法用法及代碼示例
- Python String translate()用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python String | join method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。