1

这是脚本的一部分。它应该在始终相同的名称之前获取数字(在这种情况下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

4 回答 4

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']
于 2013-06-16T18:24:47.753 回答
4

find返回找到子字符串的索引(作为整数),如果没有找到匹配的子字符串,则返回 -1。无论哪种情况,结果都是不可迭代的整数。

也许你最好做一些类似的事情:

for cow in cows.split(' cows '):
    print cow
于 2013-06-16T18:23:53.907 回答
1

for cow in cows.find(" cows ")

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

阅读该find方法。

你也许在寻找split()

>>> "111 cows 222 cows ".split(" cows ")
['111', '222', '']
于 2013-06-16T18:24:32.043 回答
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 
于 2013-06-16T18:29:39.067 回答