The Wayback Machine - https://web.archive.org/web/20220723080558/https://www.geeksforgeeks.org/python-get-the-indices-of-uppercase-characters-in-given-string/
Skip to content
Related Articles

Related Articles

Python – Get the indices of Uppercase characters in given string

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 12 Jul, 2022

Given a String extract indices of uppercase characters.

Input : test_str = ‘GeeKsFoRGeeks’ Output : [0, 3, 5, 7, 8] Explanation : Returns indices of uppercase characters. Input : test_str = ‘GFG’ Output : [0, 1, 2] Explanation : All are uppercase.

Method #1 : Using list comprehension  + range() + isupper()

In this we iterate through the indices till string length, and check for uppercase character using isupper(), if found, index is recorded.

Python3




# Python3 code to demonstrate working of
# Uppercase Indices
# Using list comprehension + range() + isupper()
 
# initializing string
test_str = 'GeeKsFoRGEEks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Uppercase check using isupper()
res = [idx for idx in range(len(test_str)) if test_str[idx].isupper()]
 
# printing result
print("Uppercase elements indices : " + str(res))

Output

The original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]

Method #2 : Using enumerate() + isupper()

In this, the indices are captured using enumerate(), and isupper() does task of uppercase check as in above method.

Python3




# Python3 code to demonstrate working of
# Uppercase Indices
# Using enumerate() + isupper()
 
# initializing string
test_str = 'GeeKsFoRGEEks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Uppercase check using isupper()
# enumerate() gets indices
res = [idx for idx, chr in enumerate(test_str) if chr.isupper()]
 
# printing result
print("Uppercase elements indices : " + str(res))

Output

The original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]

Method #3 : Without isupper() method

Python3




# Python3 code to demonstrate working of
# Uppercase Indices
# Using list comprehension + range() + isupper()
 
# initializing string
test_str = 'GeeKsFoRGEEks'
upperalphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# printing original string
print("The original string is : " + str(test_str))
res=[]
# Uppercase check
for i in range(0,len(test_str)):
    if test_str[i] in upperalphabets:
        res.append(i)
# printing result
print("Uppercase elements indices : " + str(res))

Output

The original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!