aaaabbbb
aaaabbbb

Reputation: 133

printing data in python error (list indices must be integers, not str)

I'm trying to print the data. This is my code:

print 'The first 5 tweets for \"{}\":\n'.format(keywords[0])
for txt in k1_tweets_processed[0:5]:
print txt['text']
print

This is my error:

TypeError                                 Traceback (most recent call last)
<ipython-input-81-e74a15accb5b> in <module>()
  5 print 'The first 5 tweets for \"{}\":\n'.format(keywords[0])
  6 for txt in k1_tweets_processed[0:5]:
 ----> 7     print txt['text']
  8 print
  9 

TypeError: list indices must be integers, not str

Upvotes: 0

Views: 59

Answers (3)

tjc
tjc

Reputation: 193

If you want to print the contents of k1_tweets_processed you should do something like this:

for txt in k1_tweets_processed[0:5]:
    print txt
    print

The for loop will assign the variable txt to the current value of k1_tweets_processed, then execute the two print statements for each value.

Upvotes: 0

Back2Basics
Back2Basics

Reputation: 7806

Replace line 7 with

print txt

It is likely you've already selected the text strings that you want using the for loop.

Upvotes: 0

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

print txt['text'] 

You are clearly passing a string as index, but list indices should be int, not string.

You should use this if you want to access dictionary, not list.

As both you and the error message saying this is a list, no need to use that line.

You already have list element in txt. So, try:

print txt

Upvotes: 2

Related Questions