'Int'对象不可迭代。但是,它是一个字符串

时间:2013-06-16 18:23:04

标签: python for-loop

这是脚本的一部分。它应该在名称之前得到数字,这些数字将始终相同(在cows}

的情况下
cows = "111 cows 222 cows "
for cow in cows.find(" cows "):
    startingpos = cow-4
    print(cows[startingpos:cow])

结果应为:

111 
222

但是,我正在

TypeError: 'Int' object is not iterable

即使cows是字符串,也不是整数,为什么?

4 个答案:

答案 0 :(得分:7)

str.find()会返回int,而不是str

尝试以下方法:

cows = "111 cows 222 cows "
print cows.split(" cows ") # this prints ['111', '222', '']

最后一个空条目可能不受欢迎,可以轻松删除:

cows = "111 cows 222 cows "
cows_lst = [cow for cow in cows.split(" cows ") if cow]
print cows_lst # now it prints ['111', '222']

答案 1 :(得分:4)

find返回找到子字符串的索引(作为整数),如果找不到子字符串匹配则返回-1。在任何一种情况下,结果都是一个不可迭代的整数。

也许你最好做一些像:

for cow in cows.split(' cows '):
    print cow

答案 2 :(得分:1)

for cow in cows.find(" cows ")

这里,find()返回一个整数索引,不能迭代。

了解find方法。

您是在寻找split()吗?

>>> "111 cows 222 cows ".split(" cows ")
['111', '222', '']

答案 3 :(得分:0)

str.find上的帮助:

>>> print str.find.__doc__
S.find(sub [,start [,end]]) -> int        #returns an integer

Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.

也许你想做这样的事情,使用str.find解决方案:

cows = "111 cows 222 cows "
start = 0                          # search starts from this index
cow = cows.find('cows', start)     # find the index of 'cows'
while cow != -1:                   # loop until cow != -1
    startingpos = cow - 4
    print(cows[startingpos:cow])   
    start = cow + 1                # change the value of start to cow + 1
                                   # now search will start from this new index
    cow = cows.find('cows', start) #search again

<强>输出:

111 
222