0

The aim of the script is to allow the user to input a word and also input a character they wish to find in the string. It will then find all occurences and output the positions of the indexes. My current script runs fine so theres no syntax errors, but when i enter a character, it just does nothing. My code:

print("This program finds all indexes of a character in a string. \n")

string = input("Enter a string to search:\n")
char = input("\nWhat character to find? ")
char = char[0]

found = False
start = 0
index = start

while index < len(string):
    if string[index] == char:
        found = True

index = index + 1

if found == True:
    print ("'" + char + "' found at index", index)

if found == False:
    print("Sorry, no occurrences of '" + char + "' found")

Where is it going wrong? For it not to print out my character. Its weird, when i type in a single character for the string, i.e. "c" for both inputs, it says the index is at 1, when it should be 0.

3
  • Think about when index = index + 1 will get reached (try stepping over the code line-by-line in your head, on paper or using e.g. pythontutor.com). Commented Nov 11, 2015 at 14:52
  • Because indices start at 0 and you return the index after adding 1 to it. Commented Nov 11, 2015 at 14:52
  • Hint: Exactly as @jonrsharpe wrote. Your remark "does nothing" should be: "it endlessly loops in the while loop with index stuck at 0 forever". Commented Nov 11, 2015 at 15:00

1 Answer 1

1

There are two problems with you code:

  1. Your indentation is off in index=index+1.
  2. You are missing a break statement after the found=True line.

Also, why are you reimplementing the built in find method on strings. string.find(char) would accomplish this same task.

It is unnecessary to compare booleans to True and False. if found: and if not found: would work intead.

Sign up to request clarification or add additional context in comments.

1 Comment

I see, now although I have found the strings, It's only printing the first character found in the string. How would i print all the characters within that string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.