python如何把字符串放到列表
要把字符串放到列表中,可以使用以下方法:
- 使用
split()
方法:将字符串根据指定的分隔符分割成多个子字符串,并返回一个包含这些子字符串的列表。string = "hello world"list = string.split()# 默认以空格作为分隔符print(list)# ['hello', 'world']
- 直接使用列表推导式:
string = "hello world"list = [char for char in string]print(list)# ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
- 使用
list()
方法:string = "hello world"list = list(string)print(list)# ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']