So I have been set this task for revision and I am unsure as to what the question is implying:
Because identifiers in a programming language cannot contain any spaces, programmers use conventions when stating the names of variables and subroutines. Popular conventions include PascalCase (used in these tutorials), camelCase, kebab-case and snake_case. Write a function that takes three parameters, the two parts of an identifier, the convention required and outputs the identifier.
E.g. Shields Up in kebab-case: shields-up - All letters are in lowercase. Each word is separated with a dash.
snake_case shields_up - All letters are in lowercase. Each word is separated with an underscore
camelCase: shieldsUp - All letters are in lowercase except the first letter of the second word.
PascalCase: ShieldsUp - Only the first letter of each word is in uppercase.
I assume that the code is asking for the identifier to be displayed in each of these conventions. I have tired looking up ways to turn a string into camelCase but that is as far as I have got.
If anyone has any ideas, please let me know! Thanks
CodePudding user response:
Off the top of my head, a simple approach for camelCase would be:
>>> def conventionalIdentifier(str1, str2, convention):
... if(convention == 'camelcase'):
... return str1.lower() str2.capitalize()
... else: #similarly for the rest
... pass
...
>>> print(conventionalIdentifier('hello', 'there', 'camelcase'))
helloThere
From what I gather, the question specifies that you take two parts of an identifier, i.e. you just have to put two strings together in a particular format.
CodePudding user response:
This may look like a lot of code for something so trivial but it's designed to show how you can modularise the approach thus making it more extensible should you need to add other styles.
Furthermore, this allows the user to pass multiple words that need to be constructed into the specified style. Rather than call different functions, just call one with a parameter indicating the required style.
def kebab(args):
return '-'.join([arg.lower() for arg in args])
def snake(args):
return '_'.join([arg.lower() for arg in args])
def camel(args):
output = [args[0].lower()]
for arg in args[1:]:
output.append(arg[0].upper() arg[1:].lower())
return ''.join(output)
def pascal(args):
output = []
for arg in args:
output.append(arg[0].upper() arg[1:].lower())
return ''.join(output)
CONVENTION = {'k': kebab, 's': snake, 'c': camel, 'p': pascal}
def process(c, args):
if (func := CONVENTION.get(c.lower(), None)):
return func(args)
return None
print(process('s', ['My', 'name','is','jake']))