Open In App

Python – Convert Snake case to Pascal case

Last Updated : 02 Jun, 2023
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)



Similar Reads

Python program to convert camel case string to snake case
Given a string in camel case, write a Python program to convert the given string from camel case to snake case.Examples: Input : GeeksForGeeks Output : geeks_for_geeks Input : ThisIsInCamelCase Output : this_is_in_camel_case Let's see the different ways we can do this task. Method #1 : Naive ApproachThis is a naive implementation to convert camel c
4 min read
Python - Convert Snake Case String to Camel Case
Given a snake case string, convert to camel case. Input : test_str = 'geeksforgeeks_is_best_for_geeks' Output : geeksforgeeksIsBestForGeeks Explanation : String converted to Camel Case. Input : test_str = 'geeksforgeeks_best_for_geeks' Output : geeksforgeeksBestForGeeks Explanation : String converted to Camel Case. Method #1: Using split() + join()
4 min read
Python program to print Pascal's Triangle
Pascal's triangle is a pattern of the triangle which is based on nCr, below is the pictorial representation of Pascal's triangle. Example: Input: N = 5Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1Method 1: Using nCr formula i.e. n!/(n-r)!r! After using nCr formula, the pictorial representation becomes: 0C0 1C0 1C1 2C0 2C1 2C2 3C0 3C1 3C2 3C3Algorithm: Take
3 min read
Create a Snake-Game using Turtle in Python
A snake game is an arcade maze game which has been developed by Gremlin Industries and published by Sega in October 1976. It is considered to be a skillful game and has been popularized among people for generations. The snake in the Snake game is controlled using the four direction buttons relative to the direction it is headed in. The player's obj
10 min read
Snake Water Gun game using Python and C
Snake Water Gun is one of the famous two-player game played by many people. It is a hand game in which the player randomly chooses any of the three forms i.e. snake, water, and gun. Here, we are going to implement this game using python. This python project is to build a game for a single player that plays with the computer Following are the rules
8 min read
Snake Game in Python - Using Pygame module
Snake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of fruits without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginner-friendly projects that every novice programmer s
15+ min read
Snake Game Using Tkinter - Python
For many years, players all across the world have cherished the iconic video game Snake. The player controls a snake that crawls around the screen while attempting to consume food, avoiding obstacles or running into its own tail. It is a straightforward but addictive game. The snake lengthens each time it consumes food, and the player must control
12 min read
PyQt5 - Snake Game
In this article, we will see how we can design a simple snake game using PyQt5. Snake is the common name for a video game concept where the player maneuvers a line that grows in length, with the line itself being a primary obstacle. The concept originated in the 1976 arcade game Blockade, and the ease of implementing Snake has led to hundreds of ve
14 min read
AI Driven Snake Game using Deep Q Learning
Content has been removed from this Article
1 min read
Python regex to find sequences of one upper case letter followed by lower case letters
Write a Python Program to find sequences of one upper case letter followed by lower case letters. If found, print 'Yes', otherwise 'No'. Examples: Input : GeeksOutput : YesInput : geeksforgeeksOutput : NoPython regex to find sequences of one upper case letter followed by lower case lettersUsing re.search() To check if the sequence of one upper case
2 min read
Practice Tags :