将字符串转换为列表Python
时间:2020-02-23 14:42:13 来源:igfitidea点击:
在本教程中,我们将看到如何将字符串转换为Python列表。
我们可以使用String的拆分函数将字符串转换为列表。
字符串 split
函数
Python字符串拆分函数签名
str.split(sep=None, maxsplit=-1)
参数
sep:将用作分隔符的字符串参数。
maxsplit:拆分的次数
让我们看一些例子。
使用没有任何参数的split
如果我们不提供任何分隔符,则默认情况下将按空格拆分。
str = "Hello world from theitroad" # call split function list1=str.split() print(str) print('List of words: ',list1)
使用分隔符逗号
str = "San Franceco,China,Nepal,Bhutan" # call split function listOfCountries=str.split(',') print(str) print('List of countries:',listOfCountries)
输出:
San Franceco,China,Nepal,Bhutan List of countries: ['San Franceco', 'China', 'Nepal', 'Bhutan']
将字符串转换为字符列表
我们可以使用列表函数将字符串转换为字符列表。
str = "Hello world" # call split function list1=list(str) print(str) print('List of words: ',list1) print(str1)