Open In App

Python – Uppercase Half String

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, perform uppercase of the later part of the string.

Input : test_str = 'geeksforgeek' 
Output : geeksfORGEEK 
Explanation : Latter half of string is uppercased. 
Input : test_str = 'apples' 
Output : appLES 
Explanation : Latter half of string is uppercased.

Method #1 : Using upper() + loop + len()

In this, we compute the half index and then perform upper() to only those characters which lie in the other half of the string.

Python3




# Python3 code to demonstrate working of
# Uppercase Half String
# Using upper() + loop + len()
 
# initializing string
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# computing half index
hlf_idx = len(test_str) // 2
 
res = ''
for idx in range(len(test_str)):
 
    # uppercasing later half
    if idx >= hlf_idx:
        res += test_str[idx].upper()
    else:
        res += test_str[idx]
 
# printing result
print("The resultant string : " + str(res))


Output

The original string is : geeksforgeeks
The resultant string : geeksfORGEEKS

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #2 : Using list comprehension + join() + upper()

This is similar to the above method, just the task is performed in a shorthand manner using list comprehension.

Python3




# Python3 code to demonstrate working of
# Uppercase Half String
# Using list comprehension + join() + upper()
 
# Initializing string
test_str = 'geeksforgeeks'
 
# Printing original string
print("The original string is : " + str(test_str))
 
# Computing half index
hlf_idx = len(test_str) // 2
 
# join() used to create result string
res = ''.join([test_str[idx].upper() if idx >= hlf_idx else test_str[idx]
               for idx in range(len(test_str))])
 
# Printing result
print("The resultant string : " + str(res))


Output

The original string is : geeksforgeeks
The resultant string : geeksfORGEEKS

Time Complexity: O(n)
Auxiliary Space: O(n)

Method#3: Using String slicing and upper()

Use string slicing to divide the string into two separate sub_string and convert the right sub_string to the upper case with upper() method. 

Python3




# Python3 code to demonstrate working of
# Uppercase Half String
# Using upper() + slicing string
 
# initializing string
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# computing half index
hlf_idx = len(test_str) // 2
 
# Making new string with half upper case
# Using slicing
# slicing takes one position less to ending position provided
res = test_str[:hlf_idx] + test_str[hlf_idx:].upper()
 
# printing result
print("The resultant string : " + str(res))


Output

The original string is : geeksforgeeks
The resultant string : geeksfORGEEKS

Time Complexity: O(n) -> (slicing)
Auxiliary Space: O(n)

Method #4 : Using slicing +index()+for loop

Python3




# Python3 code to demonstrate working of
# Uppercase Half String
 
# initializing string
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# computing half index
x = len(test_str)//2
a = test_str[x:]
b = test_str[:x]
cap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sma = "abcdefghijklmnopqrstuvwxyz"
res = ""
for i in a:
    res += cap[sma.index(i)]
res = b+res
# printing result
print("The resultant string : " + str(res))


Output

The original string is : geeksforgeeks
The resultant string : geeksfORGEEKS

Time Complexity: O(n) where n is the length of the input string.
Auxiliary Space: O(n) as we are creating a new string ‘res’ with a length equal to the length of the input string.

Method#5: using re module

Steps:

  1. Import the re module.
  2. Define a string to be processed, test_str.
  3. Print the original string.
  4. Compute the half index of the string by dividing its length by 2.
  5. Extract the second half of the string using the half index.
  6. Use regular expressions to convert all word characters in the second half of the string to uppercase.
  7. a. Use (?i) to set the regular expression to case-insensitive mode.
  8. b. Use \w+ to match all word characters in the string.
  9. c. Use a lambda function to convert each match to uppercase using the group() method of the match object.
  10. d. Replace all matches in the second half of the string with their uppercase equivalents using re.sub().
  11. Concatenate the first half of the string with the modified second half to create the result string.
  12. Print the result string.

Python3




import re
 
# initializing string
test_str = 'geeksforgeeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# computing half index
hlf_idx = len(test_str) // 2
 
# Making new string with half upper case using regular expressions
res = re.sub(r"(?i)(\w+)", lambda m: m.group().upper(), test_str[hlf_idx:])
 
# concatenating the two parts of the string
result = test_str[:hlf_idx] + res
 
# printing result
print("The resultant string : " + str(result))


Output

The original string is : geeksforgeeks
The resultant string : geeksfORGEEKS

Time complexity: O(n), where n is the length of the input string. This is because the regular expression pattern is applied to the second half of the string, which has length n/2. The time complexity of re.sub() is proportional to the length of the input string, so the overall time complexity is O(n/2 + n/2) = O(n).

Auxiliary space: O(n), where n is the length of the input string. This is because the re.sub() function creates a new string containing the modified second half of the input string, and the result string also has length n. The space used by the other variables (e.g., test_str, hlf_idx, res) is constant, regardless of the length of the input string.

Method #6: Using string concatenation and conditional operator

Steps:

  1. Initialize the string variable test_str.
  2. Calculate the length of the string and store it in the length variable.
  3. Initialize an empty string variable result.
  4. Use a for loop to iterate through the string characters.
    • Use a conditional operator to check if the index of the character is less than half of the string length.
    • If the above condition is true, concatenate the character with the result variable.
    • If the above condition is false, concatenate the uppercase of the character with the result variable.
  5. Print the result variable.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Uppercase Half String
# Using string concatenation and conditional operator
 
# Iializing string
test_str = 'geeksforgeeks'
 
# Printing original string
print("The original string is : " + str(test_str))
 
# Computing half index
length = len(test_str)
hlf_idx = length // 2
 
# Initializing result string
result = ''
 
# Iterating through characters
for i in range(length):
 
    # Conditional operator
    result += test_str[i] if i < hlf_idx else test_str[i].upper()
 
# Printing result
print("The resultant string : " + str(result))


Output

The original string is : geeksforgeeks
The resultant string : geeksfORGEEKS

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), as we are using an extra variable result to store the output string.

Method#7:Using itertools, islice(), and string concatenation:

Algorithm :

  1. Initialize the input string test_str and compute its half index hlf_idx.
  2. Use the islice function from the itertools module to iterate over the characters of test_str from the beginning until the end, and assign each character to the variable c.
  3. For each character c, use a list comprehension to:
  4. Check if its index i is greater than or equal to hlf_idx.
  5. If so, convert the character to uppercase using the upper() method and append it to a list.
  6. If not, append the character as is to the list.
  7. Use the join() method to concatenate the list of characters into a new string res.
  8. Print the new string res.

Python3




from itertools import islice
 
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
  
hlf_idx = len(test_str) // 2
 
res = "".join([c.upper() if i >= hlf_idx else c for i, c in enumerate(islice(test_str, None))])
 
# printing result
print("The resultant string : " + str(res))
#This code is contributed by Jyothi pinjala.


Output

The original string is : geeksforgeeks
The resultant string : geeksfORGEEKS

Time complexity: O(n), where n is the length of the input string test_str. This is because the code iterates over the characters of the string exactly once, and each iteration takes constant time.

Auxiliary space: O(N), where n is the length of the input string test_str. This is because the code creates a list of the characters of the string and then joins them back into a string, using an additional list to hold the characters of the new string. Both the original and the new string require O(n) space. The islice object created by the islice function also requires O(1) space.

Method 8: Using built-in function map() + the ternary operator.

Steps:

  1. Get the length of the string and find the half index by dividing it by 2 and using the floor division operator to get an integer value.
  2. Use map() to apply the ternary operator on each character of the string. If the index of the character is greater than or equal to the half index, return the character in uppercase, otherwise return the original character.
  3. Convert the map object to a string using the join() method.
  4. Assign the resultant string to the variable res.
  5. Print the original string and the resultant string.

Python3




test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
 
hlf_idx = len(test_str) // 2
 
res = ''.join(map(lambda c: c.upper() if test_str.index(c) >= hlf_idx else c, test_str))
 
# printing result
print("The resultant string : " + str(res))


Output

The original string is : geeksforgeeks
The resultant string : geeksfORgeeks

Time complexity: O(N), where n is the length of the string. 
Auxiliary space: O(N) because the new string is created in memory.



Similar Reads

Python - Test if String contains any Uppercase character
Given a String, Test if it contains any uppercase character. Input : test_str = 'geeksforgeeks' Output : False Explanation : No uppercase character in String.Input : test_str = 'geeksforgEeks' Output : True Explanation : E is uppercase in String. Method #1 : Using loop + isupper() In this, we iterate for each character in String, check for uppercas
6 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', sub_list = ["best", "geeksforgeeks"] Output : GEEKSF
7 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() + isupper() In this, we iterate through the indices til
5 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.Input : test_list = ["Gfg", "is", "best", "for", "
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 of random characters and digits. Let's see how we
3 min read
Python | Ways to split strings on Uppercase characters
Given a string, write a Python program to split strings on Uppercase characters. Let's discuss a few methods to solve the problem. Method #1: Using re.findall() method C/C++ Code # Python code to demonstrate # to split strings # on uppercase letter import re # Initialising string ini_str = 'GeeksForGeeks' # Printing Initial string print (&quot;Init
4 min read
Python - Uppercase Nth character
The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the Nth character of the string to uppercase. Let’s discuss certain ways in which this can be performed. Method #1 : Using string slicing + upper() This task can easily be performed usi
5 min read
Python program to Count Uppercase, Lowercase, special character and numeric values using Regex
Prerequisites: Regular Expression in Python Given a string. The task is to count the number of Uppercase, Lowercase, special character and numeric values present in the string using Regular expression in Python. Examples: Input : "ThisIsGeeksforGeeks!, 123" Output :No. of uppercase characters = 4No. of lowercase characters = 15No. of numerical char
2 min read
Python - Convert Strings to Uppercase in Dictionary value lists
Given dictionary with values list, convert all the strings to upper case. Input : {"Gfg" : ["ab", "cd"], "Best" : ["gh"], "is" : ["kl"]} Output : {'Gfg': ['AB', 'CD'], 'Best': ['GH'], 'is': ['KL']} Explanation : All value lists strings are converted to upper case. Input : {"Gfg" : ["ab", "cd", "Ef"]} Output : {'Gfg': ['AB', 'CD', "EF"]} Explanation
8 min read
Python program to Uppercase selective indices
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
7 min read
Practice Tags :