python 进阶(2) -- string join


[HTML_REMOVED][HTML_REMOVED]月似当时,人似当时否?[HTML_REMOVED][HTML_REMOVED]


在 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 方法