Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator
string
camelcase

How do you convert a string to camelcase format?

Harsh Jain

What is camelcase format?

Camelcase is the practice of writing phrases without any spaces or punctuation between words. To indicate the separation between words, we isntead use a single capitalized letter for each word. Below are some examples:

  • someLabelThatNeedsToBeCamelized
  • someMixedString
  • thisIsCamelCaseString

Now, let’s look at how we can convert any given string to camelcase format.

Code

Let’s see three different kinds of strings:

  1. A string having a - (dash) as the separation between words.
  2. A string having a " " (space) as the separation between words.
  3. A string having an _ (underscore) as the separation between words.

We will be using the re package in Python to first replace - and _ with a space. Then, we will capitalize the first character of each word. Finally, we will join all of the words together.

Let’s take a look at the code now:

from re import sub

def camel(s):
  s = sub(r"(_|-)+", " ", s).title().replace(" ", "")
  return ''.join([s[0].lower(), s[1:]])

print(camel('some_string_with_underscore'))
print(camel('Some string with Spaces'))
print(camel('some-string-with-dashes'))
print(camel('some string-with dashes_underscores and spaces'))
Convert a string to camelcase format in Python

Explanation

  • In line 1, we import the required package.

  • In line 3, we define a function (camel()) that will accept the string we want to convert.

  • In line 4, we use the sub() function from the re package to replace the occurrence of some characters from the string. Let us understand what is going on in this line step-by -tep:

    • The first parameter is the regex that will search for - and _ characters in the string, and will replace those with the second parameter value, i.e., " " (space). The third parameter is the string in which you want to perform this operation.

    • Then, we use the title() function to convert the first character in each word to upper case.

    • Finally, we use the replace() function to remove all of the " " (spaces).

  • In line 5, we convert the first character of our final string to lowercase, keep the rest of the string as is, and return it.

  • From lines 7-10, we call the camel() function with different types of strings and can see the output in camelcase format.

RELATED TAGS

python
communitycreator
string
camelcase
RELATED COURSES

View all Courses

Keep Exploring