首页 > 解决方案 > 将 finditer() 输出放入数组

问题描述

我试图在一个字符串中找到所有“TRN”的索引,我已经完成了,但是我想将所有索引放入一个数组中,我似乎做不到。

    import re

    string = 'a string with TRN, then another TRN'

    for match in re.finditer('TRN', string):
        spots = match.start()
        print(spots)

输出是:

14  
32  

我想要的输出是:
[14, 32]

我已经尝试将它放入数组并像这样附加输出,但结果是 NONE NONE。

    import re

    into_array = []

    string = 'a string with TRN, then another TRN'

    for match in re.finditer('TRN', string):
        spots = match.start()
        x = into_array.append(spots)
        print(x)

输出是:

None  
None  

任何帮助将不胜感激。

标签: pythondjango

解决方案


您正在打印append(不输出任何内容,因此None)的输出,而不是spots您想要的。

import re

into_array = []

string = 'a string with TRN, then another TRN'

for match in re.finditer('TRN', string):
    spots = match.start()
    into_array.append(spots)
print(into_array)

推荐阅读