简体   繁体   English

如何在Python中将字符串的每个字符转换为list元素的各个元素?

[英]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.

相关问题 如何将字符串转换为单个字符元组列表? - How can I convert a string into a list of individual character tuples? 在 Python 中将每个列表元素转换为字符串 - Convert each list element to string in Python 如何使用Python转换字符串中的每个字符 - How to Convert Each Character in a String using Python Python:根据每个元素的第一个字符剥离字符串数组的元素 - Python: Stripping elements of a string array based on first character of each element 如何切片python列表或数组的每个单独元素 - How to slice each individual element of a python list or array 如何合并列表中的元素,直到Python中每个元素之间没有公共字符? - How to merge element in a list until there are no common character between each elements in Python? 如何将具有多个字符的字符串转换为列表,并且每个字符都是 python 中的字符串 [暂停] - How to convert a string with many characters to a list and that each character is a string in python [on hold] 在python中没有空格的每个字符后将输入字符串转换为列表 - Convert input String to List after each character without spaces in python 如何将数字从字符串提取为列表中的单个元素? - How can extract numbers from a string to a list as individual elements in python? 如何在Python中选择每个字符? - How to select each individual character in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM