Python str.capitalize() function


str.capitalize() Function in Python

The str.capitalize() function in Python converts the first character of a string to uppercase and the rest of the characters to lowercase. This function is useful when you want to ensure the string starts with a capital letter, like in proper names or sentences.

Syntax:

string.capitalize()
  • string: The string that you want to capitalize.

Example:

# Example 1: Capitalizing a string my_string = "hello, world!" capitalized_string = my_string.capitalize() print(capitalized_string) # Output: "Hello, world!"

In this example:

  • The string "hello, world!" becomes "Hello, world!", where only the first letter ('h') is capitalized and all other characters are converted to lowercase.

Example with mixed case:

# Example 2: String with mixed case mixed_string = "pYTHON IS fUN!" capitalized_mixed = mixed_string.capitalize() print(capitalized_mixed) # Output: "Python is fun!"

Here:

  • The first letter ('p') is capitalized, and all other characters, including uppercase letters like 'Y' and 'F', are converted to lowercase, resulting in "Python is fun!".

Example with numbers and special characters:

# Example 3: String with numbers and special characters special_string = "123abc!@#" capitalized_special = special_string.capitalize() print(capitalized_special) # Output: "123abc!@#"

In this case:

  • If the string starts with a number or special character, capitalize() leaves them unchanged and capitalizes the first alphabetic character that follows (if any).
  • Since the string starts with numbers here, no changes are made.

Key Points:

  • str.capitalize() only affects the first alphabetic character by converting it to uppercase, and all subsequent characters are converted to lowercase.
  • It does not modify the original string but returns a new string with the applied changes.
  • Non-alphabetic characters like digits, punctuation, and spaces are not affected. If the string starts with a non-alphabetic character, the first letter (if any) will still be capitalized.