David
David

Reputation: 209

Split the string and save it into a list orderly in python

In the codes,result shows "['fi', 'lou', 'you']".But i want to split the string "fi lou you",and save 'fi' in a[0], 'lou' in a[1],'you' in a[2].How can i achieve it.

a=['fi lou you'.split()]
print(a[0])  

Upvotes: 1

Views: 630

Answers (3)

Echo
Echo

Reputation: 600

Used this technique to get your desired response.

    a = "['fi', 'lou', 'you']" # This is the input string
    a = a.replace("[","").replace("]","").split()
    print a[0]

Upvotes: -2

DavidG
DavidG

Reputation: 25400

Looking at the documentation of string.split you can see that it returns a list. You are then encapsulating the result of this in another list using square brackets, [] which produces a nested list.

The solution would be to simply remove the square brackets when splitting the string

a='fi lou you'.split()
print(a[0])  
# fi

Upvotes: 2

marmeladze
marmeladze

Reputation: 6572

are you looking for

>>>a = "fi lou you".split()
>>> a
['fi', 'lou', 'you']
>>> a[0]
'fi'
>>> a[1]
'lou'
>>> a[2]
'you'
>>> 

or there is something more complicated?

Upvotes: 1

Related Questions