Saturday, September 30, 2023
HomeSoftware EngineeringThe right way to write a String Case Conversion Helper in Python

The right way to write a String Case Conversion Helper in Python


The problem

On this problem, you’ll make a perform that converts between camelCasesnake_case, and kebab-case.

It’s essential to write a perform that adjustments to a given case. It should be capable to deal with all three case sorts:

change_case("snakeCase", "snake") # "snake_case"
change_case("some-lisp-name", "camel") # "someLispName"
change_case("map_to_all", "kebab") # "map-to-all"
change_case("doHTMLRequest", "kebab") # "do-h-t-m-l-request"
change_case("invalid-inPut_bad", "kebab") # None
change_case("valid-input", "huh???") # None
change_case("", "camel") # ""

Your perform should cope with invalid enter as proven, although it can solely be handed strings. Moreover, all legitimate identifiers shall be lowercase besides when crucial, in different phrases on phrase boundaries in camelCase.

The answer in Python code

Possibility 1:

import re
def change_case(label, goal):
    if ('_' in label) + ('-' in label) + (label != label.decrease()) > 1:
        return
    if goal == 'snake':
        return re.sub('([A-Z])', r'_1', label.exchange('-', '_')).decrease()
    if goal == 'kebab':
        return re.sub('([A-Z])', r'-1', label.exchange('_', '-')).decrease()
    if goal == 'camel':
        return re.sub('([_-])([a-z])', lambda m: m.group(2).higher(), label)

Possibility 2:

def change_case(id, t):
    q = ('_' in id) + ('-' in id) + any(x.isupper() for x in set(id))
    if q > 1: return
    d = {'kebab': '-', 'snake': '_'}
    l, index = [''], 0
    for x in id:
        if not l[index] or not x.isupper() and x.isalpha() and l[index][-1].isalpha():
            l[index] += x
        elif x.isalpha():
            l.append(x)
            index += 1
        else:
            l.append('')
            index += 1
    if t in d:
        return f'{d[t]}'.be part of(x.decrease() for x in l)
    if t == 'camel':
        return ''.be part of(w.capitalize() if i else w for i,w in enumerate(l))

Possibility 3:

def change_case(id, t):
    if '_' in id and '-' in id or t not in ['snake','camel','kebab']:return None
    if not id: return ''
    if not id.islower():
        if '_' in id or '-' in id: return None
    if '-' in id:
        l=id.break up('-')
    elif '_' in id:
        l=id.break up('_')
    else:
        l,temp=[],''
        for i in id:
            if i.isupper():
                l.append(temp)
                temp=i.decrease()
            else:
                temp+=i.decrease()
        l.append(temp)
    if t=='snake':return '_'.be part of(l)
    elif t=='kebab':return '-'.be part of(l)
    else:return l[0][0]+''.be part of(i.capitalize() for i in l)[1:]

Check circumstances to validate our resolution

take a look at.it("Primary checks")
take a look at.assert_equals(change_case("snakeCase", "snake"), "snake_case", "camelCase to snake_case conversion ought to work")    
take a look at.assert_equals(change_case("some-lisp-name", "camel"), "someLispName", "kebab-case to camelCase conversion ought to work")    
take a look at.assert_equals(change_case("map_to_all", "kebab"), "map-to-all", "snake_case to kebab-case conversion ought to work")    
take a look at.assert_equals(change_case("doHTMLRequest", "kebab"), "do-h-t-m-l-request", "camelCase to kebab-case conversion ought to work")    
take a look at.assert_equals(change_case("invalid-inPut_bad", "kebab"), None, "mIx-ed_cAse enter ought to be thought-about invalid")    
take a look at.assert_equals(change_case("valid-input", "huh???"), None, "Invalid goal circumstances ought to be handled")    
take a look at.assert_equals(change_case("", "camel"), "", "An empty string shouldn't be modified.")
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments