1

I have written this to get the index of first character of string s1 which has come in string s2, but doesn't give the correct answer and every time it throws different wrong answers, anyone knows why?

s1 = input ('enter the s1 string: ')
s2 = input ('enter the s2 string: ')
for i in range (0, len(s1)):
    if s1[i] in s2:
        n= (s1.index(s1[i]))
    else:
        n= -1
print (n)

1 Answer 1

2

You should stop iteration when match found:

s1 = input('enter the s1 string: ')
s2 = input('enter the s2 string: ')
n = -1
for i in range(0, len(s1)):
    if s1[i] in s2:
        n = i # Stop iteration when match character found.
        break
print(n)

Just reference i instead of s1.index(s1[i]).

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

Comments

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.