Python uses the string split and join methods to split and splice strings, and describes these two methods. Split and join methods of string
Operating System. path. splie ()/OS. path. join () for the imported OS module seems to have different processing mechanisms, but the functions are the same.
1. string. split (str = '', num = string. count (str): string separated by str. if num has a specified value, only the num sub-string is separated.
S. split ([sep [, maxsplit])-> returns a list of strings separated by separators (sep. If the maximum number of splits is specified, the limit ends at the maximum split.
If the delimiter is not specified or is none, the default delimiter is space.
Note: The delimiter cannot be blank. Otherwise, an error may occur, but there may be separators that do not include them.
OS. path. split ()
OS. path. split splits file names and paths by path, for example, d: \ python. ext, which can be divided into ['d: \ python ', 'python.exe']
The code is as follows:
Import OS
Print OS. path. split ('C: \ Program File \ 123.doc ')
Print OS. path. split ('C: \ Program File \\')
----------------- Output ---------------------
('C: \ Program File ', '123.doc ')
('C: \ Program File ','')
2. string. join (sep): use string as the delimiter to combine all elements (represented by strings) in sep into a new string.
Concatenate all the elements of the string, ancestor, and list in the join statement into a new string using a separator (string, ancestor, and list are sequential, with the same access method)
OS. path. join (path1 [, path2 [,...]) returns the result after combining multiple paths. the parameters before the first absolute path are ignored.
The code is as follows:
>>> OS. path. join ('C: \ ', 'csv', 'test.csv ')
'C: \ csv \ test.csv'
>>> OS. path. join ('Windows \ temp ', 'C: \', 'csv', 'test.csv ')
'C: \ csv \ test.csv'
>>> OS. path. join ('/home/A','/home/aa/bb ','/home/aa/bb/C ')
'/Home/aa/bb/C'
Example:
Write a function. the parameter is a long string and a word. replace the word in the long string with the corresponding number of letters. ** for example, if the long string is "this hack is wack hack" and the word is "hack", the function output is required: "this ***** is wack ****"
The code is as follows:
Def censor (text, word ):
Texts = text. split ("")
For I in range (len (texts): if texts [I] = word:
Texts [I] = "*" * len (word)
Return "". join (texts)
Print censor ("hey", "hey ")
Output:
*********