Identify the correct output of the following Python Code: Str = 'Hello World!…

2023

Identify the correct output of the following Python Code:
Str = 'Hello World! Hello India!'
Pos = Str.index ('Hello')
print (Pos)

  1. A.

    0 / 0

  2. B.

    13 / 13

  3. C.

    [0, 13] / [0, 13]

  4. D.

    (0, 13) / (0, 13)

Attempted by 1459 students.

Show answer & explanation

Correct answer: A

Correct output: 0

Corrected code example: Str = 'Hello World! Hello India!' Pos = Str.index('Hello') print(Pos)

Explanation:

  • The index() method returns the index of the first occurrence of the substring, using 0-based indexing.

  • In the string, the first "Hello" starts at index 0, so Pos becomes 0 and print(Pos) outputs 0.

  • The second "Hello" starts at index 13. index('Hello') does not return that; to find the second occurrence you can use index with a start argument, for example Str.index('Hello', 1) or use find with a start position.

  • Note: .find returns -1 when the substring is not found, while .index raises a ValueError if the substring is missing.

  • If you need all occurrence indices, search in a loop (advance the start position) or use regular expressions to collect them.

Explore the full course: Rssb Senior Computer Instructor