DEV Community

Cover image for Python ๐Ÿ challenge_30โš”๏ธ
Mahmoud EL-kariouny
Mahmoud EL-kariouny

Posted on

Python ๐Ÿ challenge_30โš”๏ธ

Convert string to camel case

  • Complete the method/function so that it converts dash/underscore Delimited words into camel casing.
  • The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).

Examples:

    "the-stealth-warrior" gets converted -> "theStealthWarrior"
    "The_Stealth_Warrior" gets converted -> "TheStealthWarrior"
Enter fullscreen mode Exit fullscreen mode
Task URL: Link

My Solution:

def to_camel_case(text):

    if len(text) > 1:

        if not text[0].isupper():
            case_one = ''.join(x for x in text.title() if x.isalnum())
            return case_one[0].lower() + case_one[1:]

        elif text[0].isupper():
            case_tow = ''.join(x for x in text.title() if x.isalnum())
            return case_tow

    else:
        return ''
Enter fullscreen mode Exit fullscreen mode

Code Snapshot:

Image description

Learn Python

Python top free courses from Coursera๐Ÿ๐Ÿ’ฏ๐Ÿš€

๐ŸŽฅ

Connect with Me ๐Ÿ˜Š

๐Ÿ”— Links

linkedin

twitter

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
leonardobispo profile image
Leonardo Bispo โ€ข

same but much more simple

def to_camel_case(text: str) -> str:
    return text[0] + ''.join(x for x in text.title()[1:] if x.isalnum) if text else ''
Enter fullscreen mode Exit fullscreen mode
Collapse
 
claudiogi profile image
ClaudioGi โ€ข โ€ข Edited

This does not work as expected, but this does:

def camelCaseOf(text):
    return text[0] + ''.join(c for c in text.title()[1:] if c not in ["_","-"])
print(camelCaseOf("turn_to_camel_case"))
print(camelCaseOf("change-to-camel-case"))
print(camelCaseOf("switch-to_camel-case"))
Enter fullscreen mode Exit fullscreen mode

output:

turnToCamelCase
changeToCamelCase
switchToCamelCase
Enter fullscreen mode Exit fullscreen mode

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay