Home >Backend Development >Python Tutorial >How to turn a string into a list in python
The split() function in Python slices the string by specifying the delimiter. If the parameter num has a specified value, num 1 substring is separated.
split() function syntax:
str.split(str="", num=string.count(str)).
Parameters: str -- delimiter, the default is all empty characters, including spaces, newlines (\n), tabs (\t), etc. num – the number of divisions. The default is -1, which separates everything.
Return value: Returns the split string list.
The following examples show how to use the split() function to convert a string into a list:
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"; print str.split( ); # 以空格为分隔符,包含 \n print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个
The output results of the above examples are as follows:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] ['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
The following examples are marked with # Separator, specify the second parameter as 1, and return two parameter lists.
txt = "Google#Runoob#Taobao#Facebook" # 第二个参数为 1,返回两个参数列表 x = txt.split("#", 1) print x
The output results of the above examples are as follows:
['Google', 'Runoob#Taobao#Facebook']
For more Python-related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to turn a string into a list in python. For more information, please follow other related articles on the PHP Chinese website!