[英]How to convert each character of a string into individual elements of list element in Python?
How can I convert a given string's individual characters into individual elements of a list in Python? 如何在Python中将给定字符串的单个字符转换为列表的单个元素?
b = []
a = "golf"
for i in a:
print(i)
b.append(i)
I expect an output as: 我期望输出为:
b = ['g','o','l','f']
but the actual output is 但实际输出是
g
o
l
f
a = "golf"
b = list(a)
print (b)
simple as that. 就那么简单。
I expect an output as: 我期望输出为:
b = ['g','o','l','f'] b = ['g','o','l','f']
That's what you'd get if you tried (after the loop): 如果尝试过(循环之后),这就是您得到的:
print("b = {}".format(b))
but since there's no such thing in your code, there's no reason it should be printed... 但是因为您的代码中没有这样的东西,所以没有理由应该打印它。
but the actual output is 但实际输出是
g G
o Ø
l 升
f F
Well yes, that's what you asked for: 是的,这就是您要的:
# ...
for i in a:
print(i) # <- HERE
# ...
Maybe you can try this: 也许您可以尝试以下方法:
b = []
a = "golf"
for i in a:
b.append(i)
b
The expected output will be: 预期的输出将是:
['g','o','l','f']
Or: 要么:
b = []
a = "golf"
for i in a:
b.append(i)
print("b = {}".format(b))
and you will get this output: 您将获得以下输出:
b = ['g','o','l','f']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.