Print word from list

E

eschneider92

pie='apple keylime pecan meat pot cherry'
pie.split()

How can I print a word from the list other than this way: print(pie[0:5]) ?

Thanks in advance.
 
C

Chris Angelico

pie='apple keylime pecan meat pot cherry'
pie.split()

How can I print a word from the list other than this way: print(pie[0:5]) ?

The split() method returns a list, it doesn't change the original string. Try:

pies = pie.split()
print(pie[2])

ChrisA
 
S

Steven D'Aprano

pie='apple keylime pecan meat pot cherry'

That sets pie to a string containing multiple words.
pie.split()

This splits pie into individual words, then immediately throws the result
away, leaving pie still set to a string. Instead, you want to do this:

pie = pie.split()

Now pie will be a list of individual words. You can print the entire list:

print(pie)


or print each word separately:


for filling in pie:
print(filling)


Or pick out one specific filling:


print(pie[2]) # should print 'pecan'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top