Python - Get the indices of Uppercase characters in given string
Last Updated :
03 Mar, 2023
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))
OutputThe original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]
Time Complexity: O(n)
Auxiliary Space: O(n)
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))
OutputThe original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]
Time Complexity: O(n)
Auxiliary Space: O(n)
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))
OutputThe original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using ord() function
Python3
# Python3 code to demonstrate working of
# Uppercase Indices
# initializing string
test_str = 'GeeKsFoRGEEks'
# printing original string
print("The original string is : " + str(test_str))
res=[]
# Uppercase check
for i in range(0,len(test_str)):
if ord(test_str[i]) in range(65,91):
res.append(i)
# printing result
print("Uppercase elements indices : " + str(res))
OutputThe original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using operator.countOf() method
Python3
# Python3 code to demonstrate working of
# Uppercase Indices
# Using operator.countOf() method
import operator as op
# 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 op.countOf(upperalphabets, test_str[i]) > 0:
res.append(i)
# printing result
print("Uppercase elements indices : " + str(res))
OutputThe original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#5: Using Recursive method.
Python3
# Python3 code to demonstrate working of
# Uppercase Indices
# Using recursive method
def uppercase_indices(string, idx=0, result=None):
if result is None:
result = []
if idx == len(string):
return result
if string[idx].isupper():
result.append(idx)
return uppercase_indices(string, idx + 1, result)
# initializing string
test_str = 'GeeKsFoRGEEks'
# printing original string
print("The original string is : " + str(test_str))
res=uppercase_indices(test_str)
# printing result
print("Uppercase elements indices : " + str(res))
#this code contributed by tvsk
OutputThe original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#6: Using re and finditer function
Python3
import re
# initializing string
test_str = 'GeeKsFoRGEEks'
# printing original string
print("The original string is : " + str(test_str))
# Finding indices of uppercase characters using re.finditer
res = [match.start() for match in re.finditer(r'[A-Z]', test_str)]
# printing result
print("Uppercase elements indices : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#7:numpy():
Algorithm:
1.Convert the given string into a list of characters using the list() method.
2.Create a numpy array from the list of characters using the np.array() method.
3.Use the np.char.isupper() method to check whether each character is uppercase or not.
4.Convert the numpy array to a list using the tolist() method.
5.Use the np.where() method to find the indices where the characters are uppercase.
6.Convert the indices to a list and return the list.
Python3
import numpy as np
test_str = 'GeeKsFoRGEEks'
# printing original string
print("The original string is : " + str(test_str))
arr = np.array(list(test_str))
res = list(np.where(np.char.isupper(arr.tolist()))[0])
print("Uppercase elements indices : " + str(res))
#This code is contributed by Jyothi pinjala
Output:
The original string is : GeeKsFoRGEEks
Uppercase elements indices : [0, 3, 5, 7, 8, 9, 10]
Time complexity: O(n)
The time complexity of the code is O(n) because it involves converting the string to a list, creating a numpy array, and then checking whether each character in the array is uppercase or not. All these operations take O(n) time.
Space complexity: O(n)
The space complexity of the code is O(n) because it involves creating a list of characters from the string, creating a numpy array from the list, and then creating a list from the numpy array. All these operations require O(n) space.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read