Python program to Uppercase selective indices
Last Updated : 11 May, 2023
Given a String perform uppercase to particular indices.
Input : test_str = ‘geeksgeeksisbestforgeeks’, idx_list = [5, 7, 3, 2, 6, 9]
Output : geEKsGEEkSisbestforgeeks
Explanation : Particular indices are uppercased.
Input : test_str = ‘geeksgeeksisbestforgeeks’, idx_list = [5, 7, 3]
Output : geeKsGeEksisbestforgeeks
Explanation : Particular indices are uppercased.
Method #1 : Using loop + upper()
In this, we perform the task of converting to uppercase using upper(), and convert to uppercase by checking indices from list.
Python3
test_str = 'geeksgeeksisbestforgeeks' print ( "The original string is : " + str (test_str)) idx_list = [ 5 , 7 , 3 , 2 , 6 , 9 ] res = '' for idx in range ( 0 , len (test_str)): if idx in idx_list: res + = test_str[idx].upper() else : res + = test_str[idx] print ( "Transformed String : " + str (res)) |
Output The original string is : geeksgeeksisbestforgeeks Transformed String : geEKsGEEkSisbestforgeeks
Method #2 : Using list comprehension + upper() + join()
A similar method as above, the difference being list comprehension is used to offer one-liner, and join() is used to convert back to a string.
Python3
test_str = 'geeksgeeksisbestforgeeks' print ( "The original string is : " + str (test_str)) idx_list = [ 5 , 7 , 3 , 2 , 6 , 9 ] res = ''.join([test_str[idx].upper() if idx in idx_list else test_str[idx] for idx in range ( 0 , len (test_str))]) print ( "Transformed String : " + str (res)) |
Output The original string is : geeksgeeksisbestforgeeks Transformed String : geEKsGEEkSisbestforgeeks
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using index() and join() methods
Python3
test_str = 'geeksgeeksisbestforgeeks' print ( "The original string is : " + str (test_str)) idx_list = [ 5 , 7 , 3 , 2 , 6 , 9 ] loweralphabets = "abcdefghijklmnopqrstuvwxyz" upperalphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" res = '' test_str = list (test_str) for i in idx_list: test_str[i] = upperalphabets[loweralphabets.index(test_str[i])] print ( "Transformed String : " + "".join(test_str)) |
Output The original string is : geeksgeeksisbestforgeeks Transformed String : geEKsGEEkSisbestforgeeks
Method #4 : Using Map and Enumerate, Lambda Function
This method uses the built-in enumerate function to keep track of the indices while looping through the string. It then uses a lambda function to check if the current index is present in the idx_list, and if so, converts the corresponding character to uppercase. Finally, the result is obtained by converting the list of characters back to a string using join.
Python3
test_str = 'geeksgeeksisbestforgeeks' print ( "The original string is : " + str (test_str)) idx_list = [ 5 , 7 , 3 , 2 , 6 , 9 ] res = ''.join( list ( map ( lambda x: x[ 1 ].upper() if x[ 0 ] in idx_list else x[ 1 ], enumerate (test_str)))) print ( "Transformed String : " + str (res)) |
Output The original string is : geeksgeeksisbestforgeeks Transformed String : geEKsGEEkSisbestforgeeks
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 5 : utilizing the string slicing method
step-by-step approach
- Initialize a string variable test_str with the value “geeksgeeksisbestforgeeks”.
- Initialize a list variable idx_list with the values [5, 7, 3, 2, 6, 9]. These values represent the indices of the characters in test_str that should be converted to uppercase.
- Create a new string variable new_str and set its value to an empty string. This variable will be used to store the transformed string.
- Loop through each index in the range from 0 to the length of the test_str minus 1. The range() function is used to generate a sequence of integers from 0 up to, but not including, the length of test_str.
- Inside the loop, check if the current index is in the list of indices to convert (idx_list). If it is, append the uppercase version of the character at that index to new_str using the upper() method. If it’s not, append the original character at that index to new_str.
- After the loop is finished, the new_str variable will contain the transformed string. Print this string with a message to indicate that it is the transformed string.
Python3
test_str = 'geeksgeeksisbestforgeeks' idx_list = [ 5 , 7 , 3 , 2 , 6 , 9 ] new_str = '' for idx in range ( len (test_str)): if idx in idx_list: new_str + = test_str[idx].upper() else : new_str + = test_str[idx] print ( "Transformed String: " + new_str) |
Output Transformed String: geEKsGEEkSisbestforgeeks
Time complexity: O(n), where n is the length of the string.
Auxiliary space: O(n), as the new string variable requires additional space to store the transformed string.
Method 6: Using numpy:
Algorithm:
- Initialize a string (test_str) and a list of indices (idx_list).
- Create a lambda function that takes in an enumerated tuple (i.e., a tuple with the index and the corresponding
- character of the string) and returns the uppercase character if the index is in idx_list, or the original character otherwise.
- Use the map() function with the lambda function and the enumerated string (using the enumerate() function)
- to apply the transformation to each character of the string.
- Join the resulting list of characters into a string.
- Print the transformed string.
Python3
import numpy as np test_str = 'geeksgeeksisbestforgeeks' print ( "The original string is : " + str (test_str)) idx_list = [ 5 , 7 , 3 , 2 , 6 , 9 ] arr = np.array( list (test_str)) mask = np.zeros_like(arr, dtype = bool ) mask[idx_list] = True arr[mask] = np.char.upper(arr[mask]) res = ''.join(arr) print ( "Transformed String : " + str (res)) |
Output: The original string is : geeksgeeksisbestforgeeks Transformed String : geEKsGEEkSisbestforgeeks
Time complexity:
The enumerate() function has a time complexity of O(n), where n is the length of the string.
The lambda function executes in constant time O(1) for each tuple in the enumerated string.
The map() function applies the lambda function to each tuple, resulting in a total time complexity of O(n).
The join() function has a time complexity of O(n), where n is the length of the string.
Therefore, the overall time complexity of the algorithm is O(n).
Space complexity:
The space complexity of the algorithm is O(n), where n is the length of the string. This is because we need to store the original string, the transformed string, the list of indices, and the temporary tuples created by enumerate(). The size of these data structures scales linearly with the size of the input string.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â 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. Python is: A high-level language, used in web development, data science, automat
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 c
11 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
10 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 exa
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 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-frie
3 min read