描述
Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
语法
join()方法语法:str.join(sequence)
参数
- sequence -- 要连接的元素序列。且必须是对象,对象内的元素必须是字符串类型。对象可以是字符串、元组、列表和字典。
返回值
返回通过指定字符连接序列中元素后生成的新字符串。
实例
以下实例展示了join()的使用方法:
1、以某规则连接元组:
| 1 2 3 4 | >>> str="-" >>> seq=('a','b','c') >>> print str.join(seq) #Join中的参数必须是序列,而不能是元素,例如:str.join('a','b','c') a-b-c #输出 |
2、以某规则连接列表:
| 1 2 3 | >>> list=['1','2','3','4','5'] >>> print(''.join(list)) 12345 #输出 |
3、以某规则连接字典(字典只对键进行连接)
| 1 2 3 | >>> seq = {'hello':'nihao','good':2,'boy':3,'doiido':4} >>> print('-'.join(seq)) #字典只对键进行连接 boy-good-doiido-hello #输出 |
4、连接2个字符串:
| 1 2 | >>> print os.path.join("D:\\","test.txt") #连接2个字符串 D:\test.txt #输出磁盘文件绝对路径和名称 |
5、找到报告目录下最新文件的绝对路径和名称:
| 1 2 3 4 5 6 | import os import time file_dir=os.path.dirname(os.path.abspath('.'))+'\\report' lists=os.listdir(file_dir) lists.sort(key=lambda fn:os.path.getatime(file_dir+"\\"+fn)) #按修改时间排序输出目录下所有文件名称 file=os.path.join(file_dir,lists[-1]) #输出列表中最后一个文件的绝对路径和名称<br>print file |
输出:
| 1 | D:\PycharmProjects\APPTEST\appAutoTest\report\201809291118result.html |
参考:https://www.jb51.net/article/63598.htm