Python Program to Convert String to Camel Case
''.join(word.capitalize() if i != 0 else word.lower() for i, word in enumerate(input_string.split())) to convert a string to camel case in Python.Examples
How to Think About It
Algorithm
Code
def to_camel_case(s): words = s.split() if not words: return '' return words[0].lower() + ''.join(word.capitalize() for word in words[1:]) # Example usage input_string = "hello world" print(to_camel_case(input_string))
Dry Run
Let's trace 'hello world' through the code
Split string
Input string 'hello world' is split into ['hello', 'world']
Process first word
First word 'hello' is converted to lowercase 'hello'
Process remaining words
Second word 'world' is capitalized to 'World'
Join words
Join 'hello' + 'World' to get 'helloWorld'
| Step | Words List | Result String |
|---|---|---|
| After split | ['hello', 'world'] | |
| After first word lowercase | ['hello', 'world'] | hello |
| After capitalizing rest | ['hello', 'world'] | helloWorld |
Why This Works
Step 1: Splitting the string
We split the input string into words using split() so we can handle each word separately.
Step 2: Lowercase first word
The first word is made lowercase to follow camel case rules where the first word starts with a lowercase letter.
Step 3: Capitalize subsequent words
Each word after the first is capitalized to mark the start of a new word in camel case.
Step 4: Joining words
All words are joined without spaces to form the final camel case string.
Alternative Approaches
import re def to_camel_case_regex(s): words = re.split(r'\s+', s.strip()) if not words: return '' return words[0].lower() + ''.join(word.capitalize() for word in words[1:]) print(to_camel_case_regex('convert this string'))
def to_camel_case_title(s): s = s.title().replace(' ', '') return s[0].lower() + s[1:] if s else '' print(to_camel_case_title('hello world'))
Complexity: O(n) time, O(n) space
Time Complexity
The program processes each character once during splitting and joining, so it runs in linear time relative to the input string length.
Space Complexity
Extra space is used to store the list of words and the output string, both proportional to the input size.
Which Approach is Fastest?
The basic split and join method is fastest and simplest; regex adds overhead but handles edge cases better.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Split and join | O(n) | O(n) | Simple and common cases |
| Regex split | O(n) | O(n) | Handling multiple spaces and trimming |
| title() method | O(n) | O(n) | Quick conversion but less precise |