Python|将字符串拆分为字符列表
有时我们得到一个字符串,我们需要将其拆分为单独的处理。这是一个非常常见的实用程序,并且在许多领域都有应用,无论是机器学习还是 Web 开发。对其进行速记可能会有所帮助。让我们讨论一些可以做到这一点的方法。
方法 #1:使用list()
这是使用内置列表函数的内部实现来完成此特定任务的最简单方法,该函数有助于将字符串分解为其字符组件。
# Python3 code to demonstrate
# split string to character list
# using list()
# initializing string
test_string = 'GeeksforGeeks'
# printing the original string
print ("The original string is : " + str(test_string))
# using list()
# to split string to character list
res = list(test_string)
# printing result
print ("The splitted character's list is : " + str(res))
输出 :
The original string is : GeeksforGeeks
The splitted character’s list is : [‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]
方法 #2:使用map()
map函数也可用于执行此特定任务。 map函数需要使用None值来执行此任务作为第一个参数,目标字符串作为最后一个参数。仅适用于 Python2。
# Python code to demonstrate
# split string to character list
# using map()
# initializing string
test_string = 'GeeksforGeeks'
# printing the original string
print ("The original string is : " + str(test_string))
# using map()
# to split string to character list
res = list(map(None, test_string))
# printing result
print ("The splitted character's list is : " + str(res))
输出 :
The original string is : GeeksforGeeks
The splitted character’s list is : [‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。