今天了解一下 join 的用法,主要有以下两种应用:
1.“connector str”.join(seq) 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
2. os.path.join(): 将多个路径组合后返回
想了解更多 Python 基础系列文章,请参考 Python 基础知识大纲
join 应用于Sequence 对象
对字符串的操作:
str_object = "one two three four"
print(f"blank join str: {' '.join(str_object)}")
print((f"colon join str: {':'.join(str_object)}"))
# output
blank join str: o n e t w o t h r e e f o u r
colon join str: o:n:e: :t:w:o: :t:h:r:e:e: :f:o:u:r
对list的操作:
list_object = ['one', 'two', 'three', 'four']
print(f"blank join list: {' '.join(list_object)}")
print((f"colon join list: {':'.join(list_object)}"))
# output:
blank join list: one two three four
colon join list: one:two:three:four
对tuple操作:
tuple_object = ('one', 'two', 'three', 'four')
print(f"blank join tuple: {' '.join(tuple_object)}")
print((f"colon join tuple: {':'.join(tuple_object)}"))
# output:
blank join tuple: one two three four
colon join tuple: one:two:three:four
对dict操作:
dict_object = {'1':'one', '2':'two', '3':'three', '4':'four'}
print(f"blank join dict: {' '.join(dict_object)}")
print((f"colon join dict: {':'.join(dict_object)}"))
# output:
blank join dict: 1 2 3 4
colon join dict: 1:2:3:4
path.join 应用
组合path,使用平台特定的分隔符把全部给定的 path 片段连接到一起,并规范化生成的路径。
import os
print(os.path.join('user', 'my document', 'python'))
#output:
user\my document\python