Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to Title Case in Python?

Tags:

python

Example:

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

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

like image 602
daydreamer Avatar asked Oct 19 '22 14:10

daydreamer


People also ask

What is title case in python?

Definition and UsageThe title() method returns a string where the first character in every word is upper case. Like a header, or a title. If the word contains a number or a symbol, the first letter after that will be converted to upper case.

Which function converts the string into title case?

string => string. toLowerCase().

How do you write a title in Python?

The title() method returns a string with first letter of each word capitalized; a title cased string.

What does capitalize () do in Python?

The capitalize() method returns a string where the first character is upper case, and the rest is lower case.


2 Answers

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'
like image 305
Facundo Casco Avatar answered Oct 21 '22 02:10

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:]
like image 32
Ivan Chaer Avatar answered Oct 21 '22 02:10

Ivan Chaer