saiyam
saiyam

Reputation: 21

How to convert a string to a list of characters in Python?

I know the string.split() function. What I want is to convert a particular word into a list. For eg converting a string 'python' to a list ['p', 'y', 't', 'h', 'o', 'n'].

Upvotes: 1

Views: 424

Answers (1)

Aquiles Carattino
Aquiles Carattino

Reputation: 930

In Python, you have to keep in mind that there are several data types which are iterables. In practice, this means you can go through each element one by one. Strings are no different:

>>> var = 'python'
>>> var[0]
p
>>> var[1]
y

The easiest way to construct a list out of an iterable is by using list:

>>> var = 'python'
>>> new_var = list(var)
>>> print(new_var)
['p', 'y', 't', 'h', 'o', 'n']

But it is not the only way, for example, you could use list-comprehensions to achieve the same (not that I advise you to use them)

>>> var = 'python'
>>> new_var = [c for c in var]
>>> print(new_var)
['p', 'y', 't', 'h', 'o', 'n']

Keeping in mind the idea of iterables is very useful because you can also transform your variable to other data types, such as a set:

>>> var = 'python'
>>> new_var = set(var)
>>> print(new_var)
{'o', 'y', 't', 'n', 'h', 'p'}

Which for the word Python is not very impressive, but if you use another one:

>>> var = 'mississippi'
>>> new_var = set(var)
>>> new_var
{'p', 'i', 's', 'm'}

You just get the used letters.

Upvotes: 2

Related Questions