0

How can I convert a given string's individual characters into individual elements of a list in 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
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 6
    Try printing `b` – m13op22 Jul 30 '19 at 14:21
  • 5
    Simply `b = list(a)` – ForceBru Jul 30 '19 at 14:21
  • 1
    Although your approach may be an overkill it is still very fine and correct. Your only problem is the way you present it. You are printing each letter with a `print` statement which prints on separate lines. Your result is held in `b` so simply add `print(b)` after the loop – Tomerikoo Jul 30 '19 at 14:24
  • `b = ['g', 'o', 'l', 'f']` isn't output; it's a definition. This loop produces the desired value of `b` whether or not you call `print` on each individual character. – chepner Jul 30 '19 at 14:34

3 Answers3

4
a = "golf"
b = list(a)
print (b)

simple as that.

Zak M.
  • 186
  • 6
0

I expect an output as:

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

o

l

f

Well yes, that's what you asked for:

# ...
for i in a:
    print(i) # <- HERE
    # ...
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
0

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']
LIU ZHIWEN
  • 143
  • 2
  • 6