I'm trying to create a program that finds the index of a character in a string,(without using any functions other than range,if statements, while loops,or for loops) but I can't figure out how to do it. Help would be greatly appreciated.
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
what is missing in your code:
testList
variable is not define, so NameError
exception will come. if i!=char:
which must be like if test[i]==char
and print or return in this if loop. demo:
>>> range(3)
[0, 1, 2]
By enumerate :
raw_input()
. If user enters multiple characters then take first character for processing.
-1
ie -1
means character is not found in string. enumerate()
to iterate string. code:
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)
output:
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$
For Multiple character in string:
code:
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)
Output:
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$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.