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
test_str = 'GeeKsFoRGEEks'
print ( "The original string is : " + str (test_str))
res = [idx for idx in range ( len (test_str)) if test_str[idx].isupper()]
print ( "Uppercase elements indices : " + str (res))
|
Output
The 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
test_str = 'GeeKsFoRGEEks'
print ( "The original string is : " + str (test_str))
res = [idx for idx, chr in enumerate (test_str) if chr .isupper()]
print ( "Uppercase elements indices : " + str (res))
|
Output
The 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
test_str = 'GeeKsFoRGEEks'
upperalphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print ( "The original string is : " + str (test_str))
res = []
for i in range ( 0 , len (test_str)):
if test_str[i] in upperalphabets:
res.append(i)
print ( "Uppercase elements indices : " + str (res))
|
Output
The 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
test_str = 'GeeKsFoRGEEks'
print ( "The original string is : " + str (test_str))
res = []
for i in range ( 0 , len (test_str)):
if ord (test_str[i]) in range ( 65 , 91 ):
res.append(i)
print ( "Uppercase elements indices : " + str (res))
|
Output
The 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
import operator as op
test_str = 'GeeKsFoRGEEks'
upperalphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print ( "The original string is : " + str (test_str))
res = []
for i in range ( 0 , len (test_str)):
if op.countOf(upperalphabets, test_str[i]) > 0 :
res.append(i)
print ( "Uppercase elements indices : " + str (res))
|
Output
The 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
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)
test_str = 'GeeKsFoRGEEks'
print ( "The original string is : " + str (test_str))
res = uppercase_indices(test_str)
print ( "Uppercase elements indices : " + str (res))
|
Output
The 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
test_str = 'GeeKsFoRGEEks'
print ( "The original string is : " + str (test_str))
res = [match.start() for match in re.finditer(r '[A-Z]' , test_str)]
print ( "Uppercase elements indices : " + str (res))
|
Output
The 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'
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))
|
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. [GFGTABS] Python # D
3 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
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 Expressi
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 straig
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
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
Python program to count the number of characters in a String
The goal here is to count the number of characters in a string, which involves determining the total length of the string. For example, given a string like "GeeksForGeeks", we want to calculate how many characters it contains. Letâs explore different approaches to accomplish this. Using len()len() i
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 retur
3 min read
Python | Find position of a character in given string
Given a string and a character, our task is to find the first position of the occurrence of the character in the string using Python. For example, consider a string s = "Geeks" and character k = 'e', in the string s, the first occurrence of the character 'e' is at index1. Let's look at various metho
2 min read
Replace a String character at given index in Python
In Python, strings are immutable, meaning they cannot be directly modified. We need to create a new string using various methods to replace a character at a specific index. Using slicingSlicing is one of the most efficient ways to replace a character at a specific index. [GFGTABS] Python s = "h
2 min read