Tuesday, April 23, 2024
HomeSoftware Engineeringconvert a PascalCase string into snake_case in Python

convert a PascalCase string into snake_case in Python


The problem

Full the operate/methodology in order that it takes a PascalCase string and returns the string in snake_case notation. Lowercase characters might be numbers. If the tactic will get a quantity as enter, it ought to return a string.

Examples:

"TestController"  -->  "test_controller"
"MoviesAndBooks"  -->  "movies_and_books"
"App7Test"        -->  "app7_test"
1                 -->  "1"

The answer in Python code

Choice 1:

import re

def to_underscore(string):
    return re.sub(r'(.)([A-Z])', r'1_2', str(string)).decrease()    

Choice 2:

def to_underscore(string):
    string = str(string)
    camel_case = string[0].decrease()
    for c in string[1:]:
        camel_case += '_{}'.format(c.decrease()) if c.isupper() else c
    return camel_case

Choice 3:

def to_underscore(s):   
    return "".be part of(["_" + c.lower() if c.isupper() else c for c in str(s)]).strip("_")

Check instances to validate our resolution

import take a look at
from resolution import *

@take a look at.describe("Pattern exams")
def sample_tests():
    @take a look at.it("Checks")
    def it_1():
        take a look at.assert_equals(to_underscore("TestController"), "test_controller")
        take a look at.assert_equals(to_underscore("MoviesAndBooks"), "movies_and_books")
        take a look at.assert_equals(to_underscore("App7Test"), "app7_test")
        take a look at.assert_equals(to_underscore(1), "1")
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments