Stormer97

String Search

May 17th, 2013
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. import sys # so that I can use stdout
  2.  
  3. charList = [] # list to store all of the split up characters
  4. searchChar = "n" # set what character we are searching for
  5. index = 0 # counter for the loop
  6. indexList = [] # list to store the indexes at which the program finds searchChar
  7.  
  8. charList = list(input("enter your string here!\n")) # get the string from the use
  9. # then put each letter of the string in charList
  10.  
  11. while index < len(charList): # while the value of index is less than the number of indexes in charList
  12.     try:
  13.         if charList[index] == searchChar:
  14.             print(searchChar, " found at index: ", index) # if seach char is found,
  15.             # print the index at which it was found
  16.             indexList.append(index) # append this index to indexList
  17.         else:
  18.             print(searchChar, " not found at index: ", index) # if search char is NOT found at index
  19.     except TypeError:
  20.         print("ERROR: index: ", index, " is not a string!") # this is for catching errors, should never trigger
  21.     index = index + 1 # incriment the counter by 1
  22.  
  23. sys.stdout.write(("instances of " + searchChar + " were found at these indexes: "))
  24. for i in indexList: # write all index at whcih searchChar were found
  25.     sys.stdout.write((str(i) + ", "))
  26. sys.stdout.write("\n") # newline
  27. foo = input("press enter to exit") # pause
Advertisement
Add Comment
Please, Sign In to add comment