我正在尝试创建一个程序来查找字符串中字符的索引,(不使用除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")
答案 0 :(得分:0)
def find_index(needle, haystack):
for i in range(len(haystack)):
if needle == haystack[i]:
return i
else:
return -1 # didn't find it
答案 1 :(得分:0)
代码中缺少的内容:
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$