Home > database >  How do print an output separated with underscores?
How do print an output separated with underscores?

Time:09-18

In some languages, it’s common to use camel case (a variable for a user’s first name might be called firstName, and a variable for a user’s preferred first name (e.g., nickname) might be called preferredFirstName.

Python, by contrast, recommends snake case, whereby words are instead separated by underscores (_), with all letters in lowercase. For instance, those same variables would be called name, first_name, and preferred_first_name, respectively, in Python.

In a file called camel.py, implement a program that prompts the user for the name of a variable in camel case and outputs the corresponding name in snake case. Assume that the user’s input will indeed be in camel case.

What I have so far is this

def main():
   for x in camel:
          "_"
camel = input("camelCase: ")
snake = camel
print("snake_case: ", snake )

I know its wrong in probably a few places but im very new at this, doing my best. Using "for" confuses me a lot but in the assignment under "hint" it mentions using the for loop so im not sure how to tie it in. Any help is appreciated thank you.

CodePudding user response:

Get a string in camel case. Then loop over the characters, and whenever you find an uppercase character replace it by an underscore followed by the lower case version of that character.

So all you need is a loop and string operations.

CodePudding user response:

This method does what you want:

import re

def camelcase_to_snakecase(camelcase_string):
    uppers = re.findall("[A-Z]", camelcase_string)
    snakecase_string = camelcase_string

    for upper in uppers:
        snakecase_string = snakecase_string.replace(upper, "_" upper.lower())

    return snakecase_string

CodePudding user response:

import re
snake_case = re.sub('(?<!^)(?=[A-Z])', '_', 'someCamelCase').lower()

(?<!^) negative look behind start of a line (we don't want to have underscore if the first character is upper)

(?=[A-Z]) positive look ahead, matching any upper case.

Finally return copy with lower case.

  • Related