How to Make First Letter Uppercase and the Rest Lowercase in a Python String?

To make the first letter of a Python string uppercase and the remaining string lowercase, you can simply use the capitalize() method, for example, like so:

str = "FOO BAR"
cap_str = str.capitalize()

print(cap_str) #=> "Foo bar"

When using the capitalize() method, you should consider the following:

  • It returns a new string with first letter capitalized and all remaining characters in lowercase (regardless of the case in the original string);
  • It does not follow any grammar-specific capitalization rules (such as capitalizing the first letter at the start of each new sentence or after certain punctuations, etc.).

Consider, for example, the following, where there are two sentences in the string, but only the first letter of the entire string is capitalized and all remaining words are converted to lowercase:

str = "fOO BAR BAZ. Qux Qaz Quux."
cap_str = str.capitalize()

print(cap_str) #=> "Foo bar baz. qux qaz quux."

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.