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 - Test if String contains any Uppercase character
The goal is to check if a given string contains at least one uppercase letter (A-Z). Using any() and isupper()any() function, combined with isdigit(), checks if any character in a string is a digit. It efficiently scans the string and returns True if at least one digit is found.Python# Define the in
3 min read
Python program to uppercase the given characters
Given a string and set of characters, convert all the characters that occurred from character set in string to uppercase() Input : test_str = 'gfg is best for geeks', upper_list = ['g', 'e', 'b'] Output : GfG is BEst for GEEks Explanation : Only selective characters uppercased.Input : test_str = 'gf
7 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg"
8 min read
Python | Get first index values in tuple of strings
Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the fi
5 min read
Ways to split strings on Uppercase characters - Python
Splitting strings on uppercase characters means dividing a string into parts whenever an uppercase letter is encountered.For example, given a string like "CamelCaseString", we may want to split it into ["Camel", "Case", "String"]. Let's discuss different ways to achieve this.Using Regular Expression
3 min read
Get Last N characters of a string - Python
We are given a string and our task is to extract the last N characters from it. For example, if we have a string s = "geeks" and n = 2, then the output will be "ks". Let's explore the most efficient methods to achieve this in Python.Using String Slicing String slicing is the fastest and most straigh
2 min read
Split String into List of characters in Python
We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g'].Using ListThe simplest way t
2 min read
Python | Get the string after occurrence of given substring
The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python.Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
3 min read
Find the Index of a Substring in Python
Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python.Using str.find() The find() method searches for the first occurrence of the specified substring and return
3 min read
Python - Characters Index occurrences in String
Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
6 min read