OneMoreError
OneMoreError

Reputation: 7728

Splitting a string into a list

I want to split a string into a list. I have been trying this

r='ABCD'

a=r.split()
['ABCD'] 

I want something like this ['A','B','C','D']

I do not want to use any for loop for this. Is there an in built programming construct to do so ?

Upvotes: 1

Views: 126

Answers (3)

dansalmo
dansalmo

Reputation: 11686

You should also learn to use list comprehensions as way of doing this since they are very fast and useful when you want to modify the items in some way:

>>> [item for item in 'ABCD']
['A', 'B', 'C', 'D']

>>> [item for item in 'ABCDEFG' if item in 'AEIOU']
['A', 'E']

Upvotes: 0

Python Spoils You
Python Spoils You

Reputation: 394

The default for spliting a string into a list is a space. If your string was spaced, and in split(' ') it will spit when it sees a space and add each letter to the list individually.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121266

A string is a sequence, so just turn it into a list:

a = list(r)

Demo:

>>> r='ABCD'
>>> list(r)
['A', 'B', 'C', 'D']

Upvotes: 7

Related Questions