脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 将列表中的字符串连接成一个长路径的方法

python 将列表中的字符串连接成一个长路径的方法

2021-04-12 00:03JNingWei Python

今天小编就为大家分享一篇python 将列表中的字符串连接成一个长路径的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

今天实习公司分配了一个数据处理的任务。在将列表中的字符串连接成一个长路径时,我遇到了如下问题:

?
1
2
3
4
5
import os
 
path_list = ['first_directory', 'second_directory', 'file.txt']
 
print os.path.join(path_list)

发现 os.path.join 之后,依然是字符串列表。这我就纳闷了:

?
1
['first_directory', 'second_directory', 'file.txt']

细思后想明白了,os.path.join 的输入必须是一个或多个 str ,而不能是 list 。字符串列表的本质依然是list。指令把 字符串列表 理解成了一个 str ,就相当于对 单str 进行 os.path.join ,最后当然没变化啦。

于是我修改了代码:

?
1
2
3
4
5
6
7
8
9
10
import os
 
path_list = ['first_directory', 'second_directory', 'file.txt']
 
# print os.path.join(path_list)
 
head = ''
for path in path_list:
 head = os.path.join(head, path)
print head

终于将列表中的字符串连接成了一个完整的长路径:

?
1
first_directory/second_directory/file.txt

以上这篇python 将列表中的字符串连接成一个长路径的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/JNingWei/article/details/77870098

延伸 · 阅读

精彩推荐