Explain the use of the join of function in Python
- 2020-05-07 19:54:03
- OfStack
Function: string join ()
Python has two functions, join() and os.path.join (), which are as follows:
join() : concatenates an array of strings. Concatenate a string, tuple, or element in a list with the specified character (delimiter) to generate a new string
os.path.join () : returns after combining multiple paths
1. Function description
1. join() function
Syntax: 'sep'.join(seq)
Parameters that
sep: separator. Can be null
seq: sequence of elements, string, tuple, dictionary to join
The syntax above is: combine all the elements of seq into a new string with sep as the separator
Return value: returns a string generated by connecting the elements with the delimiter sep
2, os.path.join () function
Syntax: os.path.join (path1[,path2[,...]])
Return value: returns after combining multiple paths
Note: parameters before the first absolute path are ignored
2 instances
# Operates on sequences (used separately) ' ' with ':' As a separator)
>>> seq1 = ['hello','good','boy','doiido']
>>> print ' '.join(seq1)
hello good boy doiido
>>> print ':'.join(seq1)
hello:good:boy:doiido
# Manipulate the string
>>> seq2 = "hello good boy doiido"
>>> print ':'.join(seq2)
h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
# Operates on tuples
>>> seq3 = ('hello','good','boy','doiido')
>>> print ':'.join(seq3)
hello:good:boy:doiido
# Operate on the dictionary
>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>>> print ':'.join(seq4)
boy:good:doiido:hello
# Merge directory
>>> import os
>>> os.path.join('/hello/','good/boy/','doiido')
'/hello/good/boy/doiido'