Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python error: list indices must be integers, not unicode

there is my problem: i'm trying to get all numbers from a Tkinter's text widget(get's the text from a file) this way:

text = self.text_field.get(1.0, 'end')    
s = re.findall("\d+", text)

s returns something like this:

[u'0', u'15', u'320', u'235', u'1', u'1', u'150', u'50', u'2', u'2', u'20']

than i try to add tags to the text widget:

for i in s: self.text_field.tag_add('%s', '5.0', '6.0') %s[i]

and it gives an error:

list indices must be integers, not unicode

thanx for helping me :)

like image 425
Saul_Tigh Avatar asked May 10 '11 19:05

Saul_Tigh


2 Answers

In Python when you do

for x in L:
    ...

inside the body loop x is already the list element, not the index.

In your case the correction needed is simply to use % i instead of % s[i].

If in other cases you need both the list element and the index number the common Python idiom is:

for index, element in enumerate(L):
    ...
like image 199
6502 Avatar answered Nov 14 '22 22:11

6502


The message says it all. When fetching i-th element of a list you cannot use a unicode value (nor a string one) you need to provide an i which is an integer.

One thing which is not clear. If you already assign each element of the s list to variable called i, then why do you so the lookup in the list again (s[i])? I would try with:

for i in s: 
      self.text_field.tag_add('%s', '5.0', '6.0') % i
like image 38
Grzegorz Oledzki Avatar answered Nov 14 '22 23:11

Grzegorz Oledzki