Home > front end >  Function it gives me position of letter in string (python)
Function it gives me position of letter in string (python)

Time:03-28

I mean like it is gonna ask me to type some string and ask me to type one letter and gives me position of it. like "Hello" i wanna letter e it gives me position 2.

Thank you for answer

CodePudding user response:

There are two ways I know of that you could use, one makes the string into a list, making it easier to iterate through, and the other just iterates through the string.

Option #1 (String):

string = 'Hello'

for char in string:
    if char == 'e':
        break <or whatever code you want here>

Option #2 (List):

def split(string):
    return [char for char in string]
 
string = 'Hello'
for char in split(string):
    if char == 'e':
        break <or your code>

CodePudding user response:

You can use the .find method.

string = input() # Gets the input from the user
character = input() # Gets another input from the user (the character)
index = string.find(character) # This function is going to return the index of character in string
print(index   1)

It prints index 1 because the index in python (actually most languages) starts at 0

Input:
Hello
e

Output:
2

  • Related