Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Tutorial | Learn Python Programming Language
Next article icon

Python program to Uppercase selective indices

Last Updated : 11 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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))
 
 
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




# 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))
 
 
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




# 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))
 
 
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




# 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))
 
 
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 

  1. Initialize a string variable test_str with the value “geeksgeeksisbestforgeeks”.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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)
 
 
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:

  1. Initialize a string (test_str) and a list of indices (idx_list).
  2. Create a lambda function that takes in an enumerated tuple (i.e., a tuple with the index and the corresponding
  3. character of the string) and returns the uppercase character if the index is in idx_list, or the original character otherwise.
  4. Use the map() function with the lambda function and the enumerated string (using the enumerate() function)
  5. to apply the transformation to each character of the string.
  6. Join the resulting list of characters into a string.
  7. 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.



Next Article
Python Tutorial | Learn Python Programming Language
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences