[英]finding the index of the same letter in a string
目前正在與
def order(word):
for each in word:
print str(word.index(each))+ ": "+each
如果我運行order("Ranger")
,代碼可以按我的意願工作,它給了我:
0: R
1: a
2: n
....and so on until "5: r"
但是如果我輸入任何帶有重復字母的單詞,例如“hall”或“silicon”,我會得到該單詞第一次迭代的 position 值,例如:
order("Hall")
0: H
1: a
2: l
2: l
如何讓 function 返回以下內容?
0: H
1: a
2: l
3: l
str.index()
的最低索引。
您可以僅為您的目的enumerate
一個字符串:
def order(word):
for index, letter in enumerate(word):
print('{}: {}'.format(index,letter))
另外,請考慮使用 python 3.x。
由於您將其標記為 Python,因此這里是 Python 實現。
def order(word):
for i in range(len(word)):
print(i+1, ":", word[i])
order("hall")
我基本上是在遍歷單詞的長度並打印出 position 處的字符。 在您的情況下, str.index() 打印出第一次出現的字符。 希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.