How to convert string to Title Case in Python?



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

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

Asked By: daydreamer



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())
Answered By: multipleinterfaces
def capitalizeWords(s):
  return re.sub(r'w+', lambda, 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):

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.

Answered By: Laurence Gonsalves

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())
Answered By: Facundo Casco

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:]
Answered By: Ivan Chaer

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
>>> eval(b)

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).


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!

Answered By: Marc

Potential library:


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.)

Answered By: Lol

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

def to_camelcase(str):
  return ' '.join([t.title() for t in str.split()])
Answered By: Evhz
def camelCase(st):
    s = st.title()
    d = "".join(s.split())
    d = d.replace(d[0],d[0].lower())
    return d

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
Answered By: Dancan Chibole
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.