月似当时,人似当时否?html
在 python 中,一共有两个 join 方法,一个是 str.join(),另外一个是 os.path.join() ,这里只了解前一种python
官方文档
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