Hướng dẫn find all occurrences of a character in a string python - tìm tất cả các lần xuất hiện của một ký tự trong một chuỗi python

Tôi đang cố gắng tìm tất cả những sự xuất hiện của "|" trong một chuỗi.

def findSectionOffsets[text]:
    startingPos = 0
    endPos = len[text]

    for position in text.find["|",startingPos, endPos]:
        print position
        endPos = position

Nhưng tôi gặp lỗi:

    for position in text.find["|",startingPos, endPos]:
TypeError: 'int' object is not iterable

Hỏi ngày 22 tháng 10 năm 2012 lúc 10:39Oct 22, 2012 at 10:39

2

Chức năng:

def findOccurrences[s, ch]:
    return [i for i, letter in enumerate[s] if letter == ch]


findOccurrences[yourString, '|']

sẽ trả về một danh sách các chỉ số của

    for position in text.find["|",startingPos, endPos]:
TypeError: 'int' object is not iterable
0 trong đó
    for position in text.find["|",startingPos, endPos]:
TypeError: 'int' object is not iterable
1 xảy ra.

Mooncrater

3.6324 Huy hiệu vàng27 Huy hiệu bạc54 Huy hiệu Đồng4 gold badges27 silver badges54 bronze badges

Đã trả lời ngày 22 tháng 10 năm 2012 lúc 10:50Oct 22, 2012 at 10:50

Marco L.Marco L.Marco L.

1.4894 Huy hiệu vàng17 Huy hiệu bạc25 Huy hiệu Đồng4 gold badges17 silver badges25 bronze badges

3

Nếu bạn muốn chỉ mục của tất cả các lần xuất hiện của ký tự

    for position in text.find["|",startingPos, endPos]:
TypeError: 'int' object is not iterable
1 trong một chuỗi, bạn có thể làm điều này

import re
str = "aaaaaa|bbbbbb|ccccc|dddd"
indexes = [x.start[] for x in re.finditer['\|', str]]
print[indexes] # 

Bài Viết Liên Quan

Chủ Đề