python -- join()

python -- join()



月似當時,人似當時否?html


在 python 中,一共有兩個 join 方法,一個是 str.join(),另外一個是 os.path.join() ,這裏只瞭解前一種python


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.ide

簡單來說,就是將可迭代對象中的元素以 str 爲分隔符拼接返回,可是這些元素必須爲 String 類型,否則會報錯this

# 報錯
>>> 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 方法code

相關文章
相關標籤/搜索