python -- join()
python -- join()
pythonjoinos月似當(dāng)時(shí),人似當(dāng)時(shí)否?
總
在 python 中,一共有兩個(gè) join 方法,一個(gè)是 str.join(),另一個(gè)是 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.
簡(jiǎn)單來講,就是將可迭代對(duì)象中的元素以 str 為分隔符拼接返回,但是這些元素必須為 String 類型,不然會(huì)報(bào)錯(cuò)
# 報(bào)錯(cuò) >>> 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# 對(duì) list 拼接 >>> l = ["hello","pinsily"] >>> " ".join(l) 'hello pinsily'# 對(duì) string 拼接 >>> s = "hello pinsily" >>> ":".join(s) 'h:e:l:l:o: :p:i:n:s:i:l:y'# 對(duì)元組拼接 >>> t = ("hello","pinsily") >>> " ".join(t) 'hello pinsily'# 對(duì)字典拼接 >>> d = {"hello":"1","pinsily":"2","and":"3","world":"4"} >>> " ".join(d) 'hello pinsily and world'注:當(dāng)要使用大量的字符串拼接時(shí),盡量避免 + 操作,這樣會(huì)產(chǎn)生大量的臨時(shí)變量,占據(jù)內(nèi)存,可以先將其拼接到 list 中,然后使用 join 方法
轉(zhuǎn)載于:https://www.cnblogs.com/pinsily/p/7904191.html
總結(jié)
以上是生活随笔為你收集整理的python -- join()的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Win7系统电脑关机后自动开机解决办法
- 下一篇: python-列表list和元组tupl