How can I turn a string (like 'hello'
) into a list (like [h,e,l,l,o]
)?
Data type conversion or type casting in Python is a very common practice. However, converting string to list in Python is not as simple as converting an int to string or vice versa. Strings can be converted to lists using list() .
Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
Typecasting to list can be done by simply using list(set_name) . Using sorted() function will convert the set into list in a defined order. The only drawback of this method is that the elements of the set need to be sortable.
One of these methods uses split() function while other methods convert the string into a list without split() function. Python list has a constructor which accepts an iterable as argument and returns a list whose elements are the elements of iterable. An iterable is a structure that can be iterated.
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello') ['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello" >>> s[1] 'e' >>> s[4] 'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello': ... print c + c, ... hh ee ll ll oo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With