The join function in Python is very powerful. It can connect strings, tuples, and list elements with specified characters (separators) to generate a new string, and the separated character can also be a string. Next Describe this function in detail.
1. grammar
1.1 string.join()
' sep'.join(seq)
**Code analysis: **
**sep: ** represents the separator, which can be a single character such as:,.-; etc., or a string such as:'abc'.
**seq: ** represents the sequence of elements to be connected, which can be a string, tuple, list, dictionary, etc.
**Note: **'sep' and seq can only be string type, not int type and float type.
**Error example 1 ('sep' is int type): **
**Error example 2 (the element in seq is of type int): **
1.2 os.path.join()
os.path.join(Path1,Path2,Path3,...)
**Code analysis: **
Connect path1, path2, path3... etc. with \ to form a file path.
2. Specific examples
2.1 The sequence of elements to be connected is a string
Example 1—(The separator is a single character)
sep =" " #Delimiter(Space)
seq ='Happy Holidays Goddess' #The string to be concatenated
str = sep.join(seq) #Concatenate elements in a string with a separator
got the answer:
' Happy Holidays Goddess'
Example 2—(The separator is multiple characters)
sep =" (*^__^*) " #Delimiter(Space)
seq ='Happy Holidays Goddess' #The string to be concatenated
str = sep.join(seq) #Concatenate elements in a string with a separator
got the answer:
' Female(*^__^*)God(*^__^*)Section(*^__^*)day(*^__^*)fast(*^__^*)fun'
2.2 The sequence of elements to be connected is a list
Example 1—(The separator is a single character)
sep ="-" #Delimiter(-)
seq =['I','2','U'] #List to connect
str = sep.join(seq) #Connect the elements in the list with a separator
got the answer:
' I-2-U'
Example 2—(The separator is multiple characters)
sep ='-goddess-' #Delimiter(Multiple characters)
seq =['I','you','widely accepted',''] #List to connect
str = sep.join(seq)
got the answer:
' I-goddess-you-goddess-widely accepted-goddess-'
**Note: **Tuples are similar to lists, so I won’t go into details
2.3 The sequence of elements to be connected is a dictionary
Example 1—(The separator is a single character)
sep =" " #Delimiter(Space)
seq ={'W':1,'i':2,'n':3,'k':4,'n':5} #Dictionary to connect
str = sep.join(seq) #Connect the elements of the dictionary with a separator
got the answer:
' W i n k'
**Note: **The dictionary only connects keys. If there are duplicates in the keys, only the first key is kept.
Example 2—(The separator is multiple characters)
sep =" (^_-) " #Delimiter(Space)
seq ={'W':1,'i':2,'n':3,'k':4,'n':5} #Dictionary to connect
str = sep.join(seq) #Connect the elements of the dictionary with a separator
got the answer:
' W (^_-) i (^_-) n (^_-) k'
2.4 The element to be connected is the path
Example 1:
path1 ='D:\\new folder'
path2 ='WeChat public account'
path3 ='16.Quick start python'
Path_Final = os.path.join(path1, path2, path3)
got the answer:
' D:\\new folder\\WeChat public account\\16.Quick start python'
# You can use the following statement to change the current path to Path_Final
os.chdir(Path_Final)
**Note: **Difference + sign connection
path1+path2+path3
got the answer:
' D:New folder WeChat public account' #No separator
**Example 2: Look at an interesting path connection and think about why? **
path1 ='D:'
path2 ='new folder:'
path3 ='WeChat public account:'
path4 ='17.Join function in python'
Path_Final = os.path.join(path1, path2, path3, path4)
got the answer:
' D:new folder:\\WeChat public account:\\17.Join function in python'
os.path.join did not add a connector \ after path1, and added a connector after path2, indicating that it is not: the result is not adding a connector, think about why there is no connector?
3. Application of join function in practice
3.1 Use python code to decompose prime factors and print them out with join function
num =int(input()) #Enter the number you want to decompose prime factors
factor_list =[] #Set to save the list of prime factors
def factor_fun(n):for i inrange(2, n+1): #Construct a loop for finding prime factors
if n%i ==0: #If n can divide i, add i to the list of prime factors
factor_list.append(i)if n!=i: #If i is not equal to n, and i is a factor of n, divide n by i to get the new number and call factor_fun function
factor_fun(int(n/i))return factor_list
c =factor_fun(num) #Call functions
print(num,'=', end=' ',sep =' ')print('*'.join('%s'%id for id in factor_list)) #Put factor_Convert the numeric data in the list into characters, use*connection
**Enter 50 to get the result: **
5050=2*5*5
3.2 Use the join function to form a new path based on the current path
import os #Import path module
os.getcwd() #Get current path
data_save = os.path.join(os.getcwd(),'data_save') #Get the current path and combine the new path
got the answer:
' C:\\Users\\Administrator\\29_Join function in python\\data_save'
3.3 Find 0. The absolute path and name of the latest file in the overall official account design directory
import os
import time
file_dir=os.path.dirname(os.path.abspath('.'))+'\\0.Overall public account design' #Get path
lists=os.listdir(file_dir) #Get the file name under the path
lists.sort(key=lambda fn:os.path.getatime(file_dir+"\\"+fn)) #Sort all file names in the output directory by modification time
file=os.path.join(file_dir,lists[-1]) #The absolute path and name of the last file in the output list
got the answer:
' D:\\new folder\\WeChat public account\\0.Overall public account design\\Seek attention to pictures.pptx'
Through the code in 3.3, batch operations can be performed on files in a certain folder.
This article is some of my opinions after using the join function. Please correct me if there is any inappropriateness.
Recommended Posts