python 进阶(2) -- string join

[HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED]月似当时,人似当时否?[HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED] [HTML_REMOVED]总[HTML_REMOVED] [HTML_REMOVED]在 python 中,一共有两个 join 方法,一个是 str.join(),另一个是 os.path.join() ,这里只了解前一种[HTML_REMOVED] [HTML_REMOVED] [HTML_REMOVED]str.join(iterable)[HTML_REMOVED] [HTML_REMOVED] [HTML_REMOVED]官方文档 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.[HTML_REMOVED] [HTML_REMOVED] [HTML_REMOVED]简单来讲,就是将可迭代对象中的元素以 str 为分隔符拼接返回,但是这些元素必须为 String 类型,不然会报错[HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED][HTML_REMOVED]# 报错 [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] l = [1,2,3] [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED] [HTML_REMOVED].join(l) Traceback (most recent call last): File [HTML_REMOVED][HTML_REMOVED]stdin[HTML_REMOVED][HTML_REMOVED], line 1, in [HTML_REMOVED]module[HTML_REMOVED] TypeError: sequence item 0: expected str instance, int found

对 list 拼接

[HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] l = [[HTML_REMOVED]hello[HTML_REMOVED],[HTML_REMOVED]pinsily[HTML_REMOVED]] [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED] [HTML_REMOVED].join(l) [HTML_REMOVED]hello pinsily[HTML_REMOVED]

对 string 拼接

[HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] s = [HTML_REMOVED]hello pinsily[HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED]:[HTML_REMOVED].join(s) [HTML_REMOVED]h:e:l:l:o: :p:i:n:s:i:l:y[HTML_REMOVED]

对元组拼接

[HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] t = ([HTML_REMOVED]hello[HTML_REMOVED],[HTML_REMOVED]pinsily[HTML_REMOVED]) [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED] [HTML_REMOVED].join(t) [HTML_REMOVED]hello pinsily[HTML_REMOVED]

对字典拼接

[HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] d = {[HTML_REMOVED]hello[HTML_REMOVED]:[HTML_REMOVED]1[HTML_REMOVED],[HTML_REMOVED]pinsily[HTML_REMOVED]:[HTML_REMOVED]2[HTML_REMOVED],[HTML_REMOVED]and[HTML_REMOVED]:[HTML_REMOVED]3[HTML_REMOVED],[HTML_REMOVED]world[HTML_REMOVED]:[HTML_REMOVED]4[HTML_REMOVED]} [HTML_REMOVED][HTML_REMOVED][HTML_REMOVED] [HTML_REMOVED] [HTML_REMOVED].join(d) [HTML_REMOVED]hello pinsily and world[HTML_REMOVED] [HTML_REMOVED][HTML_REMOVED]

[HTML_REMOVED]

[HTML_REMOVED]