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
# Python3 code to demonstrate working of
# Uppercase selective indices
# Using loop + upper()
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing indices list
idx_list = [5, 7, 3, 2, 6, 9]
res = ''
for idx in range(0, len(test_str)):
# checking for index list for uppercase
if idx in idx_list:
res += test_str[idx].upper()
else:
res += test_str[idx]
# printing result
print("Transformed String : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Uppercase selective indices
# Using list comprehension + upper() + join()
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing indices list
idx_list = [5, 7, 3, 2, 6, 9]
# one-liner way to solve this problem
res = ''.join([test_str[idx].upper() if idx in idx_list else test_str[idx]
for idx in range(0, len(test_str))])
# printing result
print("Transformed String : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Uppercase selective indices
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing indices list
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])]
# printing result
print("Transformed String : " + "".join(test_str))
OutputThe 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
# Python3 code to demonstrate working of
# Uppercase selective indices
# Using Map and Lambda and enumerate
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing indices list
idx_list = [5, 7, 3, 2, 6, 9]
# using map, lambda and enumerate
res = ''.join(list(map(lambda x: x[1].upper() if x[0] in idx_list else x[1], enumerate(test_str))))
# printing result
print("Transformed String : " + str(res))
OutputThe 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
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# initializing indices list
idx_list = [5, 7, 3, 2, 6, 9]
# create a new empty string to store the transformed string
new_str = ''
# loop through each index in the range from 0 to the length of the string minus 1
for idx in range(len(test_str)):
# if the current index is in the list of indices to convert, append the uppercase version
# of the character at that index to the new string
if idx in idx_list:
new_str += test_str[idx].upper()
# otherwise, append the original character at that index to the new string
else:
new_str += test_str[idx]
# print the transformed string
print("Transformed String: " + new_str)
OutputTransformed 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
# initializing string
test_str = 'geeksgeeksisbestforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing indices list
idx_list = [5, 7, 3, 2, 6, 9]
# converting string to numpy array
arr = np.array(list(test_str))
# creating a mask for selective indices
mask = np.zeros_like(arr, dtype=bool)
mask[idx_list] = True
# uppercase selective indices using numpy indexing
arr[mask] = np.char.upper(arr[mask])
# converting numpy array back to string
res = ''.join(arr)
# printing result
print("Transformed String : " + str(res))
#This code is contributed by Pushpa.
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 program to find maximum uppercase run
Giving a String, write a Python program to find the maximum run of uppercase characters. Examples: Input : test_str = 'GeEKSForGEEksISBESt' Output : 5 Explanation : ISBES is best run of uppercase. Input : test_str = 'GeEKSForGEEKSISBESt' Output : 10 Explanation : GEEKSISBES is best run of uppercase.
2 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 - Uppercase Selective Substrings in String
Given a String, perform uppercase of particular Substrings from List. Input : test_str = 'geeksforgeeks is best for cs', sub_list = ["best", "geeksforgeeks"] Output : GEEKSFORGEEKS is BEST for cs Explanation : geeksforgeeks and best uppercased. Input : test_str = 'geeksforgeeks is best for best', su
7 min read
Python Program to convert String to Uppercase under the Given Condition
Given a String list, the task is to write a Python program to convert uppercase strings if the length is greater than K. Examples: Input : test_list = ["Gfg", "is", "best", "for", "geeks"], K = 3 Output : ['Gfg', 'is', 'BEST', 'for', 'GEEKS'] Explanation : Best has 4 chars, hence BEST is uppercased.
5 min read
Python Program to Generate Random String With Uppercase And Digits
Generating a series of random strings can help create security codes. Besides, there are many other applications for using a random string generator, for instance, obtaining a series of numbers for a lottery game or slot machines. A random string generator generates an alphanumeric string consisting
3 min read
Python Program to Converts Characters To Uppercase Around Numbers
Given a String, the following program converts the alphabetic character around any digit to its uppercase. Input : test_str = 'geeks4geeks is best1 f6or ge8eks' Output : geekS4Geeks is besT1 F6Or gE8Ek Explanation : S and G are uppercased as surrounded by 4.Input : test_str = 'geeks4geeks best1 f6or
8 min read
Python program to find the smallest word in a sentence
Given a string S of lowercase English alphabets, the task is to print the smallest word in the given string. Examples: Input: S = âsky is blueâOutput: "is"Explanation: Length of âskyâ is 3.Length of is âisâ 2.Length of âblueâ is 4.Therefore, the smallest word is âisâ. Input: S = âgeeks for geeksâOut
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
Python - Get the indices of Uppercase characters in given string
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() + isu
5 min read
Python - Uppercase Half String
The problem is to convert half of a string to uppercase, either the first half or the second half, depending on the requirement. For example, given the string "python", the output could be "PYThon" (uppercase first half) or "pytHON" (uppercase second half).If the string length is odd, handle the mid
2 min read