Python - Convert Snake case to Pascal case
Given a string in snake_case, the task is to convert it into PascalCase, where each word starts with an uppercase letter and there are no underscores.
For Example:
Input: geeksforgeeks_is_best
Output: GeeksforgeeksIsBest
Let’s explore different methods to convert a string from snake case to Pascal case in Python.
Using split() and capitalize()
This method splits the string by underscores, capitalizes each word and then joins them back together. It is efficient in terms of both time and readability.
s= 'geeksforgeeks_is_best'
res = ''.join(word.capitalize() for word in s.split('_'))
print(res)
Output
GeeksforgeeksIsBest
Explanation:
- split('_') splits the string s into individual words at each underscore.
- capitalize() capitalizes the first letter of each word.
- ''.join() joins the list of words into a single string without any separator.
Using str.title() and replace()
This method converts a snake case string into pascal case by replacing underscores with spaces and capitalizing the first letter of each word using the title() function. After capitalizing, the words are joined back together without spaces.
s = 'geeksforgeeks_is_best'
res = s.replace("_", " ").title().replace(" ", "")
print(res)
Output
GeeksforgeeksIsBest
Explanation:
- replace("_", " ") handles the conversion of underscores to spaces.
- title() ensures that the first letter of each word is capitalized.
- replace(" ", "") removes any spaces, ensuring the result is in pascal case.
Using string.capwords()
The capwords() function from the string module automatically capitalizes words separated by spaces. We can first replace underscores with spaces, then use capwords() and finally remove spaces.
import string
s = 'geeksforgeeks_is_best'
res = string.capwords(s.replace('_', ' ')).replace(' ', '')
print(res)
Output
GeeksforgeeksIsBest
Explanation:
- s.replace('_', ' ') replaces underscores with spaces.
- string.capwords() capitalizes the first letter of each word.
- replace(' ', '') removes all spaces to form PascalCase.
Using re.sub()
Regular expressions are highly flexible and can be used to replace underscores and capitalize the first letter of each word efficiently.
import re
s= "geeksforgeeks_is_best"
res= re.sub(r"(^|_)([a-z])", lambda match: match.group(2).upper(), s)
print(res)
Output
GeeksforgeeksIsBest
Explanation:
- (^|_) matches either the start of the string (^) or an underscore (_).
- ([a-z]) matches any lowercase letter (a-z) following the start of the string s or an underscore.
- lambda match: match.group(2).upper() converts the matched lowercase letter (group 2) to uppercase.