LearnFrenzy
Sign in Take a free test

Strings · Strings Coding Problems · Question 8

Convert snake_case to camelCase and back in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Convert snake_case names to camelCase, and camelCase names back to snake_case.

Solution
main.py Run
def to_camel(name):
    first, *rest = name.split("_")
    return first + "".join(w.capitalize() for w in rest)

def to_snake(name):
    return "".join("_" + ch.lower() if ch.isupper() else ch for ch in name)

for n in ["total_marks", "is_logged_in", "user"]:
    camel = to_camel(n)
    print(n, "->", camel, "->", to_snake(camel))

Output Verified by running it on Python 3

total_marks -> totalMarks -> total_marks
is_logged_in -> isLoggedIn -> is_logged_in
user -> user -> user

Starred unpacking separates the first word, which stays lower-case. Going back, every capital becomes an underscore plus its lower-case letter.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links