![](/img/trans.png)
[英]How do you find the index positions of unescaped single curly braces in a string?
[英]How do you find the index of a character in a string?
我正在嘗試創建一個程序來查找字符串中字符的索引,(不使用除range,if循環或for循環之外的任何函數)但我無法弄清楚如何執行它。 非常感謝幫助。
def findIndex(char, test):
while char!=testList:
for i in range(len(test)):
if i!=char:
i+=1
if char==test:
print i
print findIndex("e", "alphabet")
def find_index(needle, haystack):
for i in range(len(haystack)):
if needle == haystack[i]:
return i
else:
return -1 # didn't find it
你的代碼中缺少什么:
testList
變量,因此會出現NameError
異常。 if i!=char:
必須類似於if test[i]==char
並且在此if循環中打印或返回。 演示:
>>> range(3)
[0, 1, 2]
通過枚舉 :
raw_input()
獲取用戶的字符值。 如果用戶輸入多個字符,則取第一個字符進行處理。
-1
即-1
表示在字符串中找不到字符。 enumerate()
迭代字符串。 碼:
def findIndex(char, target_inoout):
if char in target_inoout:
for i, value in enumerate(target_inoout):
if char==value:
return i
else:
return -1
char = raw_input("Enter singal Character:").strip()[0]
rs = findIndex(char, "alphabet")
if rs==-1:
print "Character %s is not found."%(char)
else:
print "Character %s is found at: %d"%(char, rs)
輸出:
vivek@vivek:~/Desktop/stackoverflow$ python 31.py
Enter singal Character:e
Character e is found at: 6
vivek@vivek:~/Desktop/stackoverflow$ python 31.py
Enter singal Character:z
Character z is not found.
vivek@vivek:~/Desktop/stackoverflow$
對於字符串中的多個字符:
碼:
def findIndex(char, target_inoout):
if char in target_inoout:
result = []
for i, value in enumerate(target_inoout):
if char==value:
result.append(i)
return result
else:
return None
char = raw_input("Enter singal Character:").strip()[0]
rs = findIndex(char, "alphabet with some more values.")
if rs:
print "Character %s is found at: %s"%(char, rs)
else:
print "Character %s is not found."%(char)
輸出:
vivek@vivek:~/Desktop/stackoverflow$ python 31.py
Enter singal Character:m
Character m is found at: [16, 19]
vivek@vivek:~/Desktop/stackoverflow$ python 31.py
Enter singal Character:z
Character z is not found.
vivek@vivek:~/Desktop/stackoverflow$
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.