Considerations when initializing a single string in a Python List

When manually traversing folders to search for files in the project, it is necessary to return the target list. It is found that Python initializes the List list to produce inconsistent results, so I will record it.

Python initializes a List. A list can be initialized with a type list()or an expression symbol , but these two initialization methods do not handle a single string consistently . When a single string is initialized with , the string will be split into a list of single characters, while with , it will be kept as an array element. Usually strings are not split, so it is recommended not to omit the symbol.[]list()[][]

Test code:

a = ['hello']; p = 'world'; a.extend(p); print('p : {}, type : {};    a : {}, type : {}'.format(p, type(p), a, type(a)))
b = ['hello']; q = [p]    ; b.extend(q); print('q : {}, type : {};    b : {}, type : {}'.format(q, type(q), b, type(b)))
c = ['hello']; r = list(p); c.extend(r); print('r : {}, type : {};    c : {}, type : {}'.format(r, type(r), c, type(c)))
d = ['hello']; s = list(q); d.extend(s); print('s : {}, type : {};    d : {}, type : {}'.format(s, type(s), d, type(d)))

# output :
# p : world                    , type : <class 'str'> ;    a : ['hello', 'w', 'o', 'r', 'l', 'd'], type : <class 'list'>
# q : ['world']                , type : <class 'list'>;    b : ['hello', 'world']                , type : <class 'list'>
# r : ['w', 'o', 'r', 'l', 'd'], type : <class 'list'>;    c : ['hello', 'w', 'o', 'r', 'l', 'd'], type : <class 'list'>
# s : ['world'                ], type : <class 'list'>;    d : ['hello', 'world']                , type : <class 'list'>

Guess you like

Origin blog.csdn.net/u012101384/article/details/131369472