How to convert string to Title Case in Python?

Python

Python Problem Overview


Example:

HILO -> Hilo
new york -> New York
SAN FRANCISCO -> San Francisco

Is there a library or standard way to perform this task?

Python Solutions


Solution 1 - Python

Why not use title Right from the docs:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

If you really wanted PascalCase you can use this:

>>> ''.join(x for x in 'make IT pascal CaSe'.title() if not x.isspace())
'MakeItPascalCase'

Solution 2 - Python

This one would always start with lowercase, and also strip non alphanumeric characters:

def camelCase(st):
    output = ''.join(x for x in st.title() if x.isalnum())
    return output[0].lower() + output[1:]

Solution 3 - Python

def capitalizeWords(s):
  return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)

re.sub can take a function for the "replacement" (rather than just a string, which is the usage most people seem to be familiar with). This repl function will be called with an re.Match object for each match of the pattern, and the result (which should be a string) will be used as a replacement for that match.

A longer version of the same thing:

WORD_RE = re.compile(r'\w+')

def capitalizeMatch(m):
  return m.group(0).capitalize()

def capitalizeWords(s):
  return WORD_RE.sub(capitalizeMatch, s)

This pre-compiles the pattern (generally considered good form) and uses a named function instead of a lambda.

Solution 4 - Python

Potential library: https://pypi.org/project/stringcase/

Example:

import stringcase
stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"

Though it's questionable whether it will leave spaces in. (Examples show it removing space, but there is a bug tracker issue noting that it leaves them in.)

Solution 5 - Python

Why not write one? Something like this may satisfy your requirements:

def FixCase(st):
    return ' '.join(''.join([w[0].upper(), w[1:].lower()]) for w in st.split())

Solution 6 - Python

Note: Why am I providing yet another answer? This answer is based on the title of the question and the notion that camelcase is defined as: a series of words that have been concatenated (no spaces!) such that each of the original words start with a capital letter (the rest being lowercase) excepting the first word of the series (which is completely lowercase). Also it is assumed that "all strings" refers to ASCII character set; unicode would not work with this solution).

simple

Given the above definition, this function

import re
word_regex_pattern = re.compile("[^A-Za-z]+")

def camel(chars):
  words = word_regex_pattern.split(chars)
  return "".join(w.lower() if i is 0 else w.title() for i, w in enumerate(words))

, when called, would result in this manner

camel("San Francisco")  # sanFrancisco
camel("SAN-FRANCISCO")  # sanFrancisco
camel("san_francisco")  # sanFrancisco

less simple

Note that it fails when presented with an already camel cased string!

camel("sanFrancisco")   # sanfrancisco  <-- noted limitation

even less simple

Note that it fails with many unicode strings

camel("México City")    # mXicoCity     <-- can't handle unicode

I don't have a solution for these cases(or other ones that could be introduced with some creativity). So, as in all things that have to do with strings, cover your own edge cases and good luck with unicode!

Solution 7 - Python

just use .title(), and it will convert first letter of every word in capital, rest in small:

>>> a='mohs shahid ss'
>>> a.title()
'Mohs Shahid Ss'
>>> a='TRUE'
>>> b=a.title()
>>> b
'True'
>>> eval(b)
True

Solution 8 - Python

def camelCase(st):
    s = st.title()
    d = "".join(s.split())
    d = d.replace(d[0],d[0].lower())
    return d

Solution 9 - Python

I would like to add my little contribution to this post:

def to_camelcase(str):
  return ' '.join([t.title() for t in str.split()])

Solution 10 - Python

From code wars - Write simple .camelCase method in Python for strings. All words must have their first letter capitalized without spaces. camelcase("hello case") => HelloCase camelcase("camel case word") => CamelCaseWord

def camel_case(string):
    titled_string = string.title()
    space_joined_string = titled_string.replace(' ', '')
    return space_joined_string

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondaydreamerView Question on Stackoverflow
Solution 1 - PythonFacundo CascoView Answer on Stackoverflow
Solution 2 - PythonIvan ChaerView Answer on Stackoverflow
Solution 3 - PythonLaurence GonsalvesView Answer on Stackoverflow
Solution 4 - PythonLolView Answer on Stackoverflow
Solution 5 - PythonmultipleinterfacesView Answer on Stackoverflow
Solution 6 - PythonMarcView Answer on Stackoverflow
Solution 7 - PythonMohammad Shahid SiddiquiView Answer on Stackoverflow
Solution 8 - PythonAishwarya SkandamaniView Answer on Stackoverflow
Solution 9 - PythonEvhzView Answer on Stackoverflow
Solution 10 - PythonDancan ChiboleView Answer on Stackoverflow