0

I have this program:

word = input('enter word:')
letter = input('enter letter to find:')

y = word.find(letter)
print(y)

and it only print 0:

enter word:pythop
enter letter to find:p
0
>>> 

so how can I get the position of both of this letter 'p' as it only recognise one of it? thanks

Joe han
  • 171
  • 11

4 Answers4

2

You got it! String position 0 is the first position in a string.

>>> 'pythop'.find('p')
0
>>> 'pythop'.find('y')
1
>>>
Mike N
  • 6,395
  • 4
  • 24
  • 21
1

Updated my answer due to typo:

I would do something like this:

word = input('enter word:')
letter = input('enter letter to find:')

y = [i for i in range(len(word)) if word.startswith(letter, i)]
print(y)

Hope this helps

magnusnn
  • 137
  • 1
  • 13
1

You do need a loop. If you only ever need to check for a single letter (not a substring), you can enumerate the characters of the word:

word = input('enter word:')
letter = input('enter letter to find:')

ys = [i for i, l in enumerate(word) if l == letter]
print(ys)
David Jones
  • 4,766
  • 3
  • 32
  • 45
0

You can use find with start and end positions. Here the docstring:

find(...)
    S.find(sub [,start [,end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.
allo
  • 3,955
  • 8
  • 40
  • 71