Python中的子串,这里有什么问题?

时间:2011-03-30 16:26:57

标签: python substring

我正在尝试在Python中模拟子字符串,但我收到错误:

    length_message = len(update)
    if length_message > 140:
        length_url    = len(short['url'])
        count_message = 140 - length_url
        update        = update["msg"][0:count_message] # Substring update variable

    print update
    return 0

错误如下:

Traceback (most recent call last):
  File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 54, in <module>
    x.updateTwitterStatus({"url": "http://xxx.com/?cat=49s", "msg": "Searching for some ....... tips?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffff "})
  File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 35, in updateTwitterStatus
    update        = update["msg"][0:count_message]
TypeError: string indices must be integers

我不能这样做?

update        = update["msg"][0:count_message]

变量“count_message”返回“120”

给我一​​个线索。

最诚挚的问候,

更新

我打这个电话,更新[“msg”]来自这里

x = TwitterC()
x.updateTwitterStatus({"url": "http://xxxx.com/?cat=49", "msg": "Searching for some ...... ....?fffffffffffffffffffffffffffffdddddddddddddddddddddddddddddssssssssssssssssssssssssssssssssssssssssssssssssssseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddfffffffffffffffffffffffffffffffffffffffffffffddddddddddddddddd"})

1 个答案:

答案 0 :(得分:6)

您是否多次循环使用此代码?

如果是这样,也许第一次通过update是一个字典,update["msg"]返回一个字符串。细

但是你设置update等于结果:

update        = update["msg"][0:int(count_message)]

(大概)是一个字符串。

如果您正在循环播放,则下次循环时会出现错误,因为现在update是一个字符串,而不是dict(因此update["msg"]不再有意义)


您可以通过在错误之前输入print语句来调试它:

print(type(update))

或者,如果不是太大,

print(repr(update))