How to capitalize a string in Python?

PythonServer Side ProgrammingProgramming

If you want to just capitalize the first letter of the first word of the string, then you can use the capitalize method from string class.

For example

>>> s = "my name"
>>> s.capitalize()
'My name'

You can also manually achieve this by string slicing.

For example

>>> s = "my name"
>>> s = s[:1].upper() + s[1:]
'My name'

If you want to capitalize each word of the string, then you should use the title method from the string class.

For example

>>> s = "my name"
>>> s.title()
'My Name'
raja
Published on 18-Dec-2017 10:52:59
Advertisements