Python – 分解字符串变量
先决条件: itertools
给定一个字符串,任务是编写一个Python程序来分解字符串并创建单个元素。
Input : GeeksForGeeks
Output : [ ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘F’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’ ]
Input: Computer
Output: [ ‘C’, ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’]
以下是执行上述任务的一些方法。
方法#1:使用join()函数
join() 方法提供了一种从可迭代对象创建字符串的灵活方法。它通过字符串分隔符(调用 join() 方法的字符串)连接可迭代对象(例如列表、字符串和元组)的每个元素,并返回连接后的字符串。
Python3
a = "GeeksForGeeks"
split_string = list(''.join(a))
print(split_string)
Python3
a = "GeeksForGeeks"
res = [i for ele in a for i in ele]
print(res)
Python3
from itertools import chain
a = "GeeksForGeeks"
# using chain.from_iterable()
# to convert list of string and characters
# to list of characters
res = list(chain.from_iterable(a))
# printing result
print(str(res))
输出:
[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘F’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]
方法#2:使用for循环
蟒蛇3
a = "GeeksForGeeks"
res = [i for ele in a for i in ele]
print(res)
输出:
[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘F’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]
方法 #3:使用 chain.from_iterable()
蟒蛇3
from itertools import chain
a = "GeeksForGeeks"
# using chain.from_iterable()
# to convert list of string and characters
# to list of characters
res = list(chain.from_iterable(a))
# printing result
print(str(res))
输出:
[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘F’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’]