Home > Backend Development > Python Tutorial > How to concatenate strings in a list into a long path in Python

How to concatenate strings in a list into a long path in Python

黄舟
Release: 2017-10-07 11:41:17
Original
2277 people have browsed it

Today the internship company assigned a data processing task. When concatenating the strings in the list into a long path, I encountered the following problem:

import os

path_list = ['first_directory', 'second_directory', 'file.txt']print os.path.join(path_list)
Copy after login

 After discovering os.path.join, it is still a list of strings. I was puzzled by this:

['first_directory', 'second_directory', 'file.txt']
Copy after login

 After thinking about it carefully, I figured out that the input of os.path.join must be one or more strs, not a list. The essence of a string list is still a list. The instruction understands the string list as a str, which is equivalent to performing os.path.join on a single str. Of course, there is no change in the end.

  So I modified the code:

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
Copy after login

  Finally the strings in the list were concatenated into a complete long path: ## #

first_directory/second_directory/file.txt
Copy after login

The above is the detailed content of How to concatenate strings in a list into a long path in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template