Try this:
- First, replace all the delimiters into a single one, i.e.
str.replace('_', '-')
- Split the string on the
str.split('-')
standardized delimiter
- Capitalize each string in list, i.e.
str.capitilize()
- Join the capitalize string with
str.join
>>> s = "the_big_red_apple"
>>> s.replace('_', '-').split('-')
['the', 'big', 'red', 'apple']
>>> ''.join(map(str.capitalize, s.replace('_', '-').split('-')))
'TheBigRedApple'
>> ''.join(word.capitalize() for word in s.replace('_', '-').split('-'))
'TheBigRedApple'
If you need to lowercase the first char, then:
>>> camel_mile = lambda x: x[0].lower() + x[1:]
>>> s = 'TheBigRedApple'
>>> camel_mile(s)
'theBigRedApple'
Alternative,
- First replace all delimiters to space
str.replace('_', ' ')
- Titlecase the string
str.title()
- Remove space from string, i.e.
str.replace(' ', '')
>>> s = "the_big_red_apple"
>>> s.replace('_', ' ').title().replace(' ', '')
'TheBigRedApple'
Another alternative,
- Iterate through the characters and then keep a pointer/note on previous character, i.e.
for prev, curr in zip(s, s[1:])
- check if the previous character is one of your delimiter, if so, uppercase the current character, i.e.
curr.upper() if prev in ['-', '_'] else curr
- skip whitepace characters, i.e.
if curr != " "
- Then add the first character in lowercase,
[s[0].lower()]
>>> chars = [s[0].lower()] + [curr.upper() if prev in ['-', '_'] else curr for prev, curr in zip(s, s[1:]) if curr != " "]
>>> "".join(chars)
'theBigRedApple'
Yet another alternative,
- Replace/Normalize all delimiters into a single one, s.replace('-', '_')
- Convert it into a list of chars,
list(s.replace('-', '_'))
- While there is still
'_'
in the list of chars, keep
- find the position of the next
'_'
- replacing the character after
'_'
with its uppercase
- replacing the
'_'
with ''
>>> s = 'the_big_red_apple'
>>> s_list = list(s.replace('-', '_'))
>>> while '_' in s_list:
... where_underscore = s_list.index('_')
... s_list[where_underscore+1] = s_list[where_underscore+1].upper()
... s_list[where_underscore] = ""
...
>>> "".join(s_list)
'theBigRedApple'
or
>>> s = 'the_big_red_apple'
>>> s_list = list(s.replace('-', '_'))
>>> while '_' in s_list:
... where_underscore = s_list.index('_')
... s_list[where_underscore:where_underscore+2] = ["", s_list[where_underscore+1].upper()]
...
>>> "".join(s_list)
'theBigRedApple'
Note: Why do we need to convert the string to list of chars? Cos strings are immutable, 'str' object does not support item assignment
BTW, the regex solution can make use of some group catching, e.g.
>>> import re
>>> s = "the_big_red_apple"
>>> upper_regex_group = lambda x: x.group(1).upper()
>>> re.sub("[_|-](\w)", upper_regex_group, s)
'theBigRedApple'
>>> re.sub("[_|-](\w)", lambda x: x.group(1).upper(), s)
'theBigRedApple'