How to use python to convert a string to a list?

Question:

As in the title, I want to convert the string 'abc' to ['abc'].

My code is as follows. Why is the codes obtained as None?

How can I write it correctly?

code = 'abc'
codes = []
if code != '':
    codes = codes.append(code)
Asked By: jaried

||

Answers:

list.append operates in-place. It doesn’t return a result (thus, it returns None. You’re assigning this to codes, hence you end up with codes = None.

You just need to call append:

code = 'abc'
codes = []
if code != '':
    codes.append(code)

better yet, use a list literal:

code = 'abc'
codes = [code] if code else []
Answered By: Alexander

You made a simple mistake. Instead of writing codes = codes.append(code) you need only codes.append(code).

Answered By: Aynos
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.