Python splits and concatenates strings

  • 2020-04-02 13:14:29
  • OfStack

About the split and join methods of strings
Os.path.splie ()/os.path.join() for the imported OS module seems to be handled differently, but functionally.

1. String. Split (STR =' ',num=string.
S.s plit ([sep [, maxsplit]]) - > A list split from a string returns a list of strings split using a separator (sep). If you specify the maximum number of partitions, it ends at maximum partition.
If the separator is not specified or is none, the separator defaults to a space.
Note: the separator cannot be empty, otherwise an error will occur, but you can have a separator that does not contain it.
OS. The path. The split ()
Os.path.split is to separate the file name and path by path, such as d:\\python\ python.ext, split as ['d:\\python', 'python.exe']

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): combine all the elements (string representation) in sep into a new string with string as the separator.
Concatenate all the elements of the string, meta-ancestor, and list in the join into a new string (string, meta-ancestor, and list are sequence types and have the same access) by delimiters.
Os.path.join (path1[,path2[,...]]) returns after combining multiple paths, and the arguments before the first absolute path are ignored.

>>> os.path.join('c:\', 'csv', 'test.csv')
'c:\csv\test.csv'
>>> os.path.join('windowstemp', 'c:\', 'csv', 'test.csv')
'c:\csv\test.csv'
>>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c')
'/home/aa/bb/c'

Example:
Write a function whose arguments are a long string and a word, change the word in the long string to the ** corresponding to the number of letters, for example, the long string is "this hack is wack hack", and the word is "hack", then the output of the function is required: "this **** is wack ****".

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 hey","hey")

Output:
* * * * * * * * *

Related articles: