HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

Case conversion Python functions

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
pythonfunctionsconversioncase

Problem

In order to capitalize the first letter of a string, you can use list slicing and the str.upper() method. Then, use str.join() to combine the capitalized first letter with the rest of the characters. Omit the lower_rest parameter to keep the rest of the string intact, or set it to True to convert to lowercase.
To decapitalize the first letter of a string, you can use the exact same method as above, but with the str.lower() method instead of str.upper().
To capitalize every word in a string, you can use the str.title() method.
To convert a string to camel case, you can use re.sub() to replace any - or _ with a space, using the regexp r"(_|-)+". Then, use str.title() to capitalize every word and convert the rest to lowercase. Finally, use str.replace() to remove any spaces between words.
To kebab case a string, you'll use the same method as above, except replace str.title() with re.sub() to match all words in the string and then use str.lower() to convert them to lowercase. Finally, use str.replace() to replace spaces with -.

Solution

def capitalize(s, lower_rest = False):
  return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])])

capitalize('fooBar') # 'FooBar'
capitalize('fooBar', True) # 'Foobar'


To capitalize every word in a string, you can use the str.title() method.
To convert a string to camel case, you can use re.sub() to replace any - or _ with a space, using the regexp r"(_|-)+". Then, use str.title() to capitalize every word and convert the rest to lowercase. Finally, use str.replace() to remove any spaces between words.
To kebab case a string, you'll use the same method as above, except replace str.title() with re.sub() to match all words in the string and then use str.lower() to convert them to lowercase. Finally, use str.replace() to replace spaces with -.
To snake case a string, you can use the same method as above, but replace the - with _.

Code Snippets

def capitalize(s, lower_rest = False):
  return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])])

capitalize('fooBar') # 'FooBar'
capitalize('fooBar', True) # 'Foobar'
def decapitalize(s, upper_rest = False):
  return ''.join([s[:1].lower(), (s[1:].upper() if upper_rest else s[1:])])

decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar', True) # 'fOOBAR'
def capitalize_every_word(s):
  return s.title()

capitalize_every_word('hello world!') # 'Hello World!'

Context

From 30-seconds-of-code: string-capitalize-camel-snake-kebab

Revisions (0)

No revisions yet.