Python 基础系列 14 - join() 应用

今天了解一下 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值