簡體   English   中英

如何使循環沿字符串繼續下去?

[英]How do I make a loop continue down a string?

st = "abXabXAbX"
ch = "A"
st = st.lower()
ch = ch.lower()


for i in st:
    if (i==ch):
       print st.find(i)

我正在嘗試在字符串“ st”中以大寫和小寫形式定位字符“ ch”。 for循環在檢測第一個“ a”時卡住了,如何檢查其他字符串繼續循環?

for循環不會被卡住,而是應按其順序前進。 您認為它被卡住了,是因為find返回它所查找項目的第一次出現 它總是在索引0處遇到它,因此您的代碼將輸出0、0、0。

為此,您可以使用枚舉來跟蹤字母的索引:

for i, ltr in enumerate(st):
    if (ltr==ch):
       print i
>>> st = "abXabXAbX".lower()
>>> ch = "A".lower()
>>> [ ix for ix,item in enumerate(st) if item == ch]
[0, 3, 6]
st = "abXabXAbX"
ch = "A"
st = st.lower()
ch = ch.lower()
pos = st.find(ch)
print(pos)

while pos >= 0:
    pos=st.find(ch,pos+1)
    if pos>-1:
        print(pos)

這會給你所有職位

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM