Home > Backend Development > Python Tutorial > How to turn a string into a list in python

How to turn a string into a list in python

Release: 2019-07-08 09:07:21
Original
23995 people have browsed it

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 ); # 以空格为分隔符,分隔成两个
Copy after login

The output results of the above examples are as follows:

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
Copy after login

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
Copy after login

The output results of the above examples are as follows:

['Google', 'Runoob#Taobao#Facebook']
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template