python -- join()

python -- join()



月似当时,人似当时否?


在 python 中,一共有两个 join 方法,一个是 str.join(),另一个是 os.path.join() ,这里只了解前一种


str.join(iterable)

官方文档
Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

简单来讲,就是将可迭代对象中的元素以 str 为分隔符拼接返回,但是这些元素必须为 String 类型,不然会报错

# 报错
>>> l = [1,2,3]
>>> " ".join(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found

# 对 list 拼接
>>> l = ["hello","pinsily"]
>>> " ".join(l)
'hello pinsily'

# 对 string 拼接
>>> s = "hello pinsily"
>>> ":".join(s)
'h:e:l:l:o: :p:i:n:s:i:l:y'

# 对元组拼接
>>> t = ("hello","pinsily")
>>> " ".join(t)
'hello pinsily'

# 对字典拼接
>>> d = {"hello":"1","pinsily":"2","and":"3","world":"4"}
>>> " ".join(d)
'hello pinsily and world'


:当要使用大量的字符串拼接时,尽量避免 + 操作,这样会产生大量的临时变量,占据内存,可以先将其拼接到 list 中,然后使用 join 方法


转载于:https://www.cnblogs.com/pinsily/p/7904191.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值