This article mainly shares with you how pythonstr extracts elements from str and replaces them in the list array. Friends who need it can take a look.
In 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 into a list whose elements are of type str.
如姓名列表str = 'Alice, Bob, John',需要将其提取为name_list = ['Alice', 'Bob', 'John']。Copy after login
In turn, sometimes it is necessary to splice the character elements in a list into a complete string according to the specified delimiter. Fortunately, the str type in Python itself comes with two methods that provide corresponding functions.
Use split
method
<list> = <str> ;.split(<separator>)
<str>
: The string that needs to be separated and extracted <separator>
: The delimiter used when extracting elements from <str2>
is generally a str type, such as ','
<list>
: Return Value, each element in the list is a separated fragment in <str>
str = 'abc,def,ghi' a = str.split(',') print(a)
1
2
3
Get the result:
['abc','def','ghi']
1
Use the join
method
< str> = <separator>.join(<list>)
##<separator>: separator, which is str type, such as
','
<list>: List object that needs to be merged, each element must be of type str
<str>: Returns a str object, It is formed by splicing each element in
<list> in order with the separator
<separator>
a = ','.join(['abc','def','ghi']) print(a)
'abc,def,ghi'
Note: When using the join method, the parameter list in the brackets must only contain members of type str Both methods are str methods, that is, .
must be of str type before
The difference between
os.path.join()
and os.path.split()
is in os
The system path separator object os.path
in the module also has two methods with the same name join()
and split()
, which are basically similar to str. The main difference is that all list type parameters of the method with the same name in str are here changed to tuple type
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 into a list whose elements are of type str.
For example, name list
str = 'Alice, Bob, John'
, it needs to be extracted asname_list = ['Alice', 'Bob', 'John' ]
.
In turn, sometimes it is necessary to splice the character elements in a list into a complete string according to the specified delimiter. Fortunately, the str type in Python itself comes with two methods that provide corresponding functions.
Related recommendations:
Convert str and list to each other in python
Python string (str) and Conversion between lists
The above is the detailed content of How to convert str and list into each other in python. For more information, please follow other related articles on the PHP Chinese website!