Get the indices of Uppercase Characters in a given String using Python

In Python, we can get the indices of uppercase characters in a given string using methods like list comprehension, for loops, and regular expressions. Finding the indices of uppercase characters can be useful in text analysis and manipulation tasks.

Method 1: Using List Comprehension

List comprehension provides a concise and efficient way to iterate through characters, check if they are uppercase using the isupper() method, and store their indices in a list ?

Syntax

indices = [index for index, char in enumerate(string) if char.isupper()]

The enumerate() function returns both the index and character from the string, allowing us to check each character and collect uppercase indices.

Example

string = "Hello World"
indices = [index for index, char in enumerate(string) if char.isupper()]
print("String:", string)
print("Uppercase indices:", indices)
String: Hello World
Uppercase indices: [0, 6]

Method 2: Using a For Loop

The for loop approach provides a more explicit and readable solution. We iterate through each character and manually check for uppercase letters ?

Example

string = "Python Is Great"
indices = []

for index, char in enumerate(string):
    if char.isupper():
        indices.append(index)

print("String:", string)        
print("Uppercase indices:", indices)
String: Python Is Great
Uppercase indices: [0, 7, 10]

Method 3: Using Regular Expressions

Regular expressions offer powerful pattern-based searching. The re.finditer() function with pattern [A-Z] identifies uppercase characters and returns match objects with position information ?

Example

import re

string = "OpenAI ChatGPT is Amazing"
indices = [match.start() for match in re.finditer(r'[A-Z]', string)]

print("String:", string)
print("Uppercase indices:", indices)
String: OpenAI ChatGPT is Amazing
Uppercase indices: [0, 4, 5, 9, 13, 14, 15, 19]

Comparison

Method Readability Performance Best For
List Comprehension High Fast Concise one-liners
For Loop Very High Good Beginners, complex logic
Regular Expressions Medium Good Complex pattern matching

Conclusion

Use list comprehension for simple, efficient solutions. Choose for loops when readability is important or when adding complex logic. Regular expressions are ideal when you need advanced pattern matching capabilities.

Updated on: 2026-03-27T08:11:36+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements