Python error: index indices must be integers, not unicode

there is my problem: I am trying to get all numbers from a text widget Tkinter (get text from a file) as follows:

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 trying to add tags to a text widget:

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

and this gives an error:

list indices must be integers, not unicode

thanx to help me :)

+5
source share
2 answers

In Python, when you do

for x in L:
    ...

inside the loop, body is xalready a list item, not an index.

In your case, correction is needed just to use % iinstead % s[i].

If in other cases you need both a list item and an index number, the general Python idiom is:

for index, element in enumerate(L):
    ...
+12

. i- unicode ( ), i, .

, . s i, (s[i])? :

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

All Articles