Xrin
Xrin

Reputation: 87

Searching for a input character in an input string in Python

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.

Upvotes: 0

Views: 3991

Answers (1)

pppery
pppery

Reputation: 3814

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.

Upvotes: 1

Related Questions