Home > Software design >  How to convert camel case into snake case in python
How to convert camel case into snake case in python

Time:12-26

Take a string from the user which is written in camel case and then convert it into snake case.

I tried using isupper method to find the uppercase letters in the string but unable to separate them.

CodePudding user response:

To convert a camel case string to snake case in Python, you can use the re module to define a regular expression that matches the pattern of a camel case string, and then use the re.sub() function to replace that pattern with the corresponding snake case string.

Here's an example of how you can do this:

import re

def camel_to_snake(name):
    # Create a regular expression to match the pattern of a camel case string
    camel_case_regex = r'([a-z0-9])([A-Z])'

    # Replace the pattern with the corresponding snake case string
    snake_case = re.sub(camel_case_regex, r'\1_\2', name).lower()

    return snake_case

# Test the function
print(camel_to_snake("camelCase")) # Output: "camel_case"
print(camel_to_snake("CamelCase")) # Output: "camel_case"
print(camel_to_snake("camelCaseString")) # Output: "camel_case_string"

This function will take a camel case string as input and return the corresponding snake case string. It uses a regular expression to match the pattern of a camel case string, which consists of a lowercase letter followed by an uppercase letter, and then replaces that pattern with the corresponding snake case string. The result is then converted to lowercase to match the standard snake case format.

CodePudding user response:

Try this:

def camel_to_snake(camel_string):
return ''.join(['_'   ch.lower() if i > 0 and ch.isupper() else ch.lower() for i, ch in enumerate(camel_string)])

Example :

snake_string = camel_to_snake("C4melCa5eString")
print(snake_string)  # Output: "c4mel_ca5e_string"

CodePudding user response:

s=input()
''.join(['_' c.lower() if c.isupper() else c for c in s]).lstrip('_')

Or you can install inflection library

pip install inflection

then:

import inflection
inflection.underscore('MyNameIsTalha')
#'my_name_is_talha'
  • Related