Home > Article > Backend Development > How to concatenate strings in a list into a long path in Python
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)
After discovering os.path.join, it is still a list of strings. I was puzzled by this:
['first_directory', 'second_directory', 'file.txt']
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
Finally the strings in the list were concatenated into a complete long path: ## #
first_directory/second_directory/file.txt
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!