Open In App

Python – Convert Snake case to Pascal case

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python Strings, we have problem in which we need to perform a case conversion of String. This a very common problem. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed.

Input : geeks_for_geeks Output : GeeksforGeeks Input : left_index Output : leftIndex

Method #1 : Using title() + replace() This task can be solved using combination of above functions. In this, we first convert the underscore to empty string and then title case each word. 

Python3




# Python3 code to demonstrate working of
# Convert Snake case to Pascal case
# Using title() + replace()
 
# initializing string
test_str = 'geeksforgeeks_is_best'
 
# printing original string
print("The original string is : " + test_str)
 
# Convert Snake case to Pascal case
# Using title() + replace()
res = test_str.replace("_", " ").title().replace(" ", "")
 
# printing result
print("The String after changing case : " + str(res))


Output

The original string is : geeksforgeeks_is_best
The String after changing case : GeeksforgeeksIsBest

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

  Method #2 : Using capwords() The task of performing title case is performed using capwords() in this method. 

Python3




# Python3 code to demonstrate working of
# Convert Snake case to Pascal case
# Using capwords()
import string
 
# initializing string
test_str = 'geeksforgeeks_is_best'
 
# printing original string
print("The original string is : " + test_str)
 
# Convert Snake case to Pascal case
# Using capwords()
res = string.capwords(test_str.replace("_", " ")).replace(" ", "")
 
# printing result
print("The String after changing case : " + str(res))


Output

The original string is : geeksforgeeks_is_best
The String after changing case : GeeksforgeeksIsBest

The time complexity is O(n), where n is the length of the input string.

The auxiliary space is O(n) as well.

Method #3 : Using split(),title() and join() methods

Python3




# Python3 code to demonstrate working of
# Convert Snake case to Pascal case
 
# initializing string
test_str = 'geeksforgeeks_is_best'
 
# printing original string
print("The original string is : " + test_str)
 
# Convert Snake case to Pascal case
x=test_str.split("_")
res=[]
for i in x:
    i=i.title()
    res.append(i)
res="".join(res)
# printing result
print("The String after changing case : " + str(res))


Output

The original string is : geeksforgeeks_is_best
The String after changing case : GeeksforgeeksIsBest

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)

Space Complexity: O(n)

Approach#4:  Using capitalize

The function splits the input string into words based on the underscore separator, capitalizes the first letter of each word, and then concatenates the words to form the output string in PascalCase.

Algorithm

1. Split the given string at “_” to form a list of words.
2. Capitalize the first letter of each word and join them.
3. Return the resulting string in Pascal case.

Python3




def snake_to_pascal_case_1(snake_str):
    words = snake_str.split("_")
    pascal_str = "".join([word.capitalize() for word in words])
    return pascal_str
snake_str='geeksforgeeks_is_best'
print(snake_to_pascal_case_1(snake_str))


Output

GeeksforgeeksIsBest

Time Complexity: O(n), where n is the length of the input string.
Auxiliary Space: O(n), where n is the length of the input string.

METHOD 5: using the split() method,

APPROACH:

In this approach, we split the string by the underscore character using the split() method, capitalize the first letter of each split word using the title() method, and then join the words using the join() method.

ALGORITHM:

1.Split the string by the underscore character using the split() method.
2.Capitalize the first letter of each split word using the title() method.
3.Join the words using the join() method.
4.Return the resulting string.

Python3




string = 'geeksforgeeks_is_best'
 
words = string.split('_')
capitalized_words = [word.title() for word in words]
result = ''.join(capitalized_words)
 
print(result)


Output

GeeksforgeeksIsBest

Time complexity: O(n), where n is the length of the input string. The split() method takes O(n) time, and the title() method takes O(m) time for each word, where m is the length of the word. The join() method takes O(n) time.

Auxiliary Space: O(n), where n is the length of the input string. The split() method creates a list of words that takes O(n) space. The capitalized_words list also takes O(n) space, and the resulting string takes O(n) space.

METHOD 6: using reduce():

  1. Initialize a string variable test_str with the input string.
  2. Split the test_str string into a list of words using the split() method and underscore (_) as the delimiter. Store the result in a list variable x.
  3. Initialize an empty list variable res to store the capitalized words.
  4. Iterate over each word in the x list using a for loop:
    a. Use the title() method to capitalize the first letter of each word, and store the result in a variable i.
    b. Append the capitalized word i to the res list.
  5. Use the join() method to concatenate the capitalized words in the res list into a single string, and store the result in a string variable res.
  6. Print the original string and the converted string.

Python3




# Python3 code to demonstrate working of
# Convert Snake case to Pascal case using reduce() method
 
from functools import reduce
 
# initializing string
test_str = 'geeksforgeeks_is_best'
 
# printing original string
print("The original string is : " + test_str)
 
# Convert Snake case to Pascal case using reduce() method
res = reduce(lambda a, b: a + b.title(), test_str.split("_"), "")
 
# printing result
print("The String after changing case : " + str(res))
#This code is contributed by Jyothi pinjala.


Output

The original string is : geeksforgeeks_is_best
The String after changing case : GeeksforgeeksIsBest

The time complexity :O(n), where n is the length of the input string, because we need to iterate over each character in the string once to split it into words, and then iterate over each word once to capitalize the first letter of each word. 

The space complexity : O(n), because we need to store the input string in memory, as well as the list of words and the list of capitalized words.

Algorithm 7:

Steps:

  1. Initialize an empty string “result”.
  2. Initialize a boolean flag “capitalize_next_word” to True.
  3. Iterate through each character in the input string.
  4. If the character is an underscore, set “capitalize_next_word” to True.
  5. If the character is not an underscore and “capitalize_next_word” is True, append the capitalized version of the character to “result” and set “capitalize_next_word” to False.
  6. If the character is not an underscore and “capitalize_next_word” is False, append the character to “result”.
  7. Return the final “result” string.

Python3




def snake_to_pascal(input_str):
    result = ""
    capitalize_next_word = True
 
    for char in input_str:
        if char == "_":
            capitalize_next_word = True
        elif capitalize_next_word:
            result += char.upper()
            capitalize_next_word = False
        else:
            result += char
 
    return result
# inputs
print(snake_to_pascal("geeks_for_geeks"))
print(snake_to_pascal("left_index"))


Output

GeeksForGeeks
LeftIndex

Time Complexity: O(n), where n is the length of the input string.

Auxiliary Space: O(1), as we are using constant extra space throughout the algorithm.

Using regular expressions

Import the regex module. Define a function that takes a snake_case string as input. Use the sub() method of the regex module to replace the underscore character with an empty string and capitalize the first letter of each word. Return the resulting string.

Python3




import re
 
# Define a function to convert snake_case to PascalCase
def snake_to_pascal_case_2(snake_str):
    # Use regular expression to match the start of the string or an underscore followed by a lowercase letter
    # and replace with the uppercase version of the letter
    return re.sub(r"(^|_)([a-z])", lambda match: match.group(2).upper(), snake_str)
 
# Example usage
snake_str = "geeksforgeeks_is_best"
print(snake_to_pascal_case_2(snake_str)) # Output: GeeksforgeeksIsBest


Output

GeeksforgeeksIsBest

Time Complexity: O(n)

Auxiliary Space: O(n)



Last Updated : 02 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads