python中join函数

源于: 功能类代码 – ClusterClass.py


"sep".join(iterable)

   join 用于以指定分隔符 sep 将可迭代对象 iterable (必须为str类型) 连接为一个新的字符串

栗子1:
分别以指定分隔符对字符串、列表、元组、字典元素进行连接

string = "test"
lis = ['w', 'e', 'q']
tpl = ('w', 'e', 'q')
dic = {"55": 5, "44": 4, "22": 2, "33": 3, "11": 1}
print("->".join(string))  # a = "11".join(string) print(a) print(type(a))
print("".join(tpl))
print(" ".join(lis))
print("key is : [%s] " % (",".join(dic)))

结果为:

t->e->s->t
weq
w e q
key is : [55,44,22,33,11] 

栗子2:
字符串去重并按从大到小排列

import os

words = "wsasdeddcewtttwssa"
words_set = set(words)  # 集合特性实现去重 字符串集合化
words_list = list(words_set)  # 集合列表化
words_list.sort(reverse=True)  # 设置排序为从大到小
new_words = "".join(words_list)  # join方法以空位分隔符拼接列表元素位新字符串
print(words_list)
print(new_words)

结果为:

['w', 't', 's', 'e', 'd', 'c', 'a']
wtsedca

os.path.join(path,path1,...)

  1. 返回多个路径拼接后的路径
  2. 忽略绝对路径之前的路径
import os
 
print(os.path.join("/user/", "test/", "python")) 
print(os.path.join("/user", "/test", "/python"), end="")  # 最后的end是取消掉print自带的换行符的

结果为:

/user/test/python
/python

学习链接:
python中join函数


拓展:
Python之字符串转列表(split),列表转字符串(join)

你可能感兴趣的:(Python编程基础,NLP,python,join函数)