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 : GeeksforGeeksInput : 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 code to demonstrate working of # Convert Snake case to Pascal case# Using title() + replace() # initializing stringtest_str = 'geeksforgeeks_is_best' # printing original stringprint("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)) |
The original string is : geeksforgeeks_is_best The String after changing case : GeeksforgeeksIsBest
Method #2 : Using capwords()
The task of performing title case is performed using capwords() in this method.
# Python3 code to demonstrate working of # Convert Snake case to Pascal case# Using capwords()import string # initializing stringtest_str = 'geeksforgeeks_is_best' # printing original stringprint("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)) |
The original string is : geeksforgeeks_is_best The String after changing case : GeeksforgeeksIsBest
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


