Python函数示例:将字符串转换为列表
发布时间:2023-06-30 06:21:06
下面是一个示例的Python函数,它将输入的字符串转换为一个列表:
def string_to_list(string):
# 使用split函数将字符串按照空格分割成多个子串
words = string.split()
# 返回转换后的列表
return words
使用这个函数可以将一个字符串转换为一个列表。例如:
input_string = "Hello World! This is a string." result_list = string_to_list(input_string) print(result_list)
输出结果为:
['Hello', 'World!', 'This', 'is', 'a', 'string.']
这个函数的实现使用了Python内置的split函数将输入的字符串按照空格进行分割,并将分割后的子串存储到一个列表中。最后,返回这个列表作为函数的输出。
需要注意的是,这个函数将字符串按照空格进行分割,因此如果字符串中包含其他的分隔符,例如逗号、句号等,需要根据具体情况进行修改。
