Join function in Python

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

Join function in Python
Functions in python
Python enumerate() function
Python function buffer
How to run id function in python
What is an anonymous function in Python
Is there a helper function in python
What is the function of adb in python
03. Operators in Python entry
How to use the round function in python
Python custom function basics
How to use the zip function in Python
12. Network Programming in Python3
print statement in python
Python built-in function -compile()
Python function basic learning
Python data analysis-apply function
How to use the format function in python
Python3 built-in function table.md
Concurrent requests in Python
Install python in Ubuntu
Context management in Python
Arithmetic operators in python
Write gui in python
Python Print print timer function
MongoDB usage in Python
Str string in Python
Computational Geometry in Python
Concurrent requests in Python (part 2)
Python high-order function usage summary!
Subscripts of tuples in Python
Noteworthy update points in Python 3.9
Python tornado upload file function
Python magic function eval () learning
How Python implements FTP function
Containerize Python applications in 3 minutes
What is introspection in python
What is object-oriented in python
Generators and iterators in Python
Python implements image stitching function
Python high-order function usage summary!
Talking about strings in Python
The usage of wheel in python
Python| function using recursion to solve
Summary of logarithm method in Python
Use of Pandas in Python development
Use nohup command instructions in python
Why doesn't Python support function overloading?
What is list comprehension in python
Learning Python third day one-line function
Getting started with Numpy in Python
Detailed sorting algorithm (implemented in Python)
How to wrap in python code
Common errors and solutions in python
Python function definition and parameter explanation
Use of numpy in Python development
Python ATM function implementation code example
What does def in python do
How to omit parentheses in Python
Detailed usage of dictionary in Python
Usage of os package in python