-2

I have this String: "----d---"

How can I find the position of the "d" in Python?

I want this ouput:

Position: 5
Jakob
  • 147
  • 1
  • 2
  • 7

2 Answers2

1

Improved answer:

def get_position(s: str, c: str):
    return s.index(c)

print("Position:", get_position("----d---", "d"))

Previous, more basic answer:

def get_position(s: str, c: str):
    for i, char in enumerate(s):
        if char == c:
            return i


print("Position:", get_position(s="----d---", c="d"))
jån
  • 165
  • 1
  • 9
0

Use rindex:

jeff = "wow bru"
print("Position:",jeff.rindex("r")+1)

Explanation:

jeff.rindex("r") returns the index of the letter r in the string assigned to jeff, and +1 just increaces that value by one, because indexing starts with 0 and we want it to start with 1.