This article is mainly to share with you pythonstr how to achieve from the STR extract elements to the list array generation, the need for small partners to look at.
In Python, it is often necessary to extract elements from the string type str into an array list, for example, STR is a comma-separated list of names, and each name needs to be extracted to a list with an element of Str.
If the name list is str = ' Alice, Bob, John ', it needs to be extracted as Name_list = [' Alice ', ' Bob ', ' John '].
In turn, it is sometimes necessary to stitch a character element in a list into a complete string by the specified delimiter. Fortunately, in Python, the STR type itself comes with two methods (method) that provide the appropriate functionality.
STR to List
How to use split
Basic use
<list> = <str>.split(<separator>)
<str>
: The string to be delimited for extraction
<separator>
: <str2>
the delimiter from which the element is extracted is usually a str type, as ','
<list>
: The return value, in which each element in the list is <str>
a fragment separated by
Example
str = ' Abc,def,ghi ' a = Str.split (', ') print (a)
Get results:
[' abc ', ' Def ', ' Ghi ']
List converted to Str
How to use join
Basic use
<str> = <separator>.join(<list>)
<separator>
: delimiter, for STR type, such as ','
<list>
: A list object that needs to be merged, where each element must be of type str
<str>
: Returns a Str object <list>
in which each element is stitched in order by a <separator>
delimiter
Example
A = ', '. Join ([' abc ', ' Def ', ' Ghi ']) print (a)
Get
' Abc,def,ghi '
Note: When using the Join method, the parameter list in parentheses must contain only members of type STR Both methods are methods of STR, that is, the .
str type must be
os.path.join()
os.path.split()
The difference between the and and
The os
system path delimiter object in the module os.path
also has two methods with the same name and join()
split()
, using basically similar to STR, the main difference is that all of the list type parameters of the method with the same name in STR are changed into a tuple type here.
In Python, it is often necessary to extract elements from the string type str into an array list, for example, STR is a comma-separated list of names, and each name needs to be extracted to a list with an element of Str.
such as the name list str = 'Alice, Bob, John'
, you need to extract it name_list = ['Alice', 'Bob', 'John']
.
In turn, it is sometimes necessary to stitch a character element in a list into a complete string by the specified delimiter. Fortunately, in Python, the STR type itself comes with two methods (method) that provide the appropriate functionality.
Related recommendations:
The STR and list in Python are converted to each other
The Python string (str) and the list are converted to each other