开发者

Python error: list indices must be integers, not unicode

开发者 https://www.devze.com 2023-03-04 02:56 出处:网络
there is my problem: i\'m trying to get all number开发者_StackOverflows from a Tkinter\'s text widget(get\'s the text from a file) this way:

there is my problem: i'm trying to get all number开发者_StackOverflows 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 :)


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):
    ...


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号