将finditer()输出放入数组

2024-09-30 14:16:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个字符串中找到所有“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]

我尝试将其放入数组并像这样附加输出,但结果是没有

    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  

任何帮助都将不胜感激


Tags: inimportreforstringmatchwithanother
1条回答
网友
1楼 · 发布于 2024-09-30 14:16:56

您正在打印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)

相关问题 更多 >

    热门问题