Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Capital indexes

Write a function named capital_indexes. The function takes a single parameter, which is a string. Your function should return a list of all the indexes in the string that have capital letters.

For example, calling capital_indexes("HeLlO") should return the list [0, 2, 4].

 

==== SOLUTION ====

“`python
def capital_indexes(s):
        indexes = [] # Create an empty list to store indexes
       for i in range(len(s)): # Iterate through the string indices
              if s[i].isupper(): # Check if the character at index i is uppercase
                     indexes.append(i) # If uppercase, add the index to the list
       return indexes # Return the list of indexes with capital letters

 

# Test the function
print(capital_indexes(“HeLlO”)) # Output: [0, 2, 4]

“`

Let’s break down the code and explain each part step by step:

1. `def capital_indexes(s):`: This line defines a function named `capital_indexes` that takes one parameter `s`, which is a string. This function will find and return the indexes of capital letters in the given string.

2. `indexes = []`: Here, we create an empty list named `indexes` to store the indexes of capital letters.

3. `for i in range(len(s)):`: This line sets up a loop that iterates through each index `i` in the range of the length of the string `s`. In simpler terms, it goes through each letter of the string one by one.

4. `if s[i].isupper():`: Inside the loop, this line checks if the character at index `i` of the string `s` is uppercase. The `isupper()` method returns `True` if the character is uppercase, and `False` otherwise.

5. `indexes.append(i)`: If the character at index `i` is uppercase, this line adds the index `i` to the `indexes` list. In other words, it remembers the position of the uppercase letter.

6. `return indexes`: After the loop finishes, this line returns the list `indexes`, which contains the indexes of all the capital letters in the string.

7. `print(capital_indexes(“HeLlO”))`: This line calls the `capital_indexes` function with the string `”HeLlO”` as an argument and prints the result. The function returns `[0, 2, 4]`, which are the indexes of the capital letters in the string `”HeLlO”`.

So, when you run this code, it will print `[0, 2, 4]`, indicating that the capital letters in the string `”HeLlO”` are located at indexes 0, 2, and 4.

Join the conversation