Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn a string into a list in Python? [duplicate]

Tags:

How can I turn a string (like 'hello') into a list (like [h,e,l,l,o])?

like image 426
Alex Millar Avatar asked Sep 22 '11 23:09

Alex Millar


People also ask

Can you turn a string into a list Python?

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() .

How do I convert a string to a 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.

How do you convert an item to a list in Python?

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.

How do I convert a string to a list without splitting in Python?

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.


1 Answers

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 
like image 91
Jeremy Avatar answered Oct 27 '22 02:10

Jeremy