Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a word to a list of chars [duplicate]

Tags:

python

I can split a sentence into individual words like so:

string = 'This is a string, with words!'
string.split(" ")
['This', 'is', 'a', 'string,', 'with', 'words!']

But I don't know how to split a word into letters:

word = "word"
word.split("")

Throws me an error. Ideally I want it to return ['w','o','r','d'] thats why the split argument is "".

like image 372
user1103294 Avatar asked Mar 14 '13 19:03

user1103294


People also ask

How do you convert words into a list?

How to Convert a String to a List of Words. 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 I split a string into a list of words?

To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters.

How do you split a word into a list of letters in Python?

Use the list() class to split a word into a list of letters, e.g. my_list = list(my_str) . The list() class will convert the string into a list of letters. Copied!

How do you split a string into a list in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.


2 Answers

>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']
like image 115
iblazevic Avatar answered Sep 25 '22 14:09

iblazevic


In Python string is iterable. This means it supports special protocol.

>>> s = '123'
>>> i = iter(s)
>>> i
<iterator object at 0x00E82C50>
>>> i.next()
'1'
>>> i.next()
'2'
>>> i.next()
'3'
>>> i.next()

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    i.next()
StopIteration

list constructor may build list of any iterable. It relies on this special method next and gets letter by letter from string until it encounters StopIteration.

So, the easiest way to make a list of letters from string is to feed it to list constructor:

>>> list(s)
['1', '2', '3']
like image 29
ovgolovin Avatar answered Sep 24 '22 14:09

ovgolovin