Introduction of join of method in python

  • 2020-12-10 00:46:12
  • OfStack

describe

The Python join() method is used to concatenate elements in a sequence to produce a new string with the specified character.

grammar

join() method syntax: ES10en. join (sequence)

parameter

sequence -- The sequence of elements to join.

The return value

Returns a new string generated by concatenating elements in a sequence by specifying characters.

The instance

The following examples show how join() is used:

1. Connect tuples with certain rules:


>>> str="-"
>>> seq=('a','b','c')
>>> print str.join(seq)
a-b-c # The output 

2. Connect the list with a certain rule:


>>> list=['1','2','3','4','5']
>>> print(''.join(list))
12345 # The output 

3. Connect the dictionary with some rule (the dictionary only connects keys)


>>> seq = {'hello':'nihao','good':2,'boy':3,'doiido':4}
>>> print('-'.join(seq)) # The dictionary only concatenates keys 
boy-good-doiido-hello # The output 

4. Connect two strings:


>>> print os.path.join("D:\\","test.txt") # The connection 2 A string 
D:\test.txt # Output the absolute path and name of the disk file 

5. Find the absolute path and name of the latest file in the report directory:


import os
import time
file_dir=os.path.dirname(os.path.abspath('.'))+'\\report'
lists=os.listdir(file_dir)
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]) # Last in the output list 1 The absolute path and name of the file 
print file

Output:


D:\PycharmProjects\APPTEST\appAutoTest\report\201809291118result.html

conclusion


Related articles: