my_str = "python is a programmming language"
result = my_str.capitalize()
print(result)
# Output
# Python is a programmming language
In Python, the capitalize() function can be used to capitalize the first letter of a string. This is useful when you want to make sure that the first letter of a string is always capitalized, such as when you are printing a name or a title. To use the capitalize() function, simply specify the string that you want to capitalize as the argument. For example, if you want to capitalize the string "python", you would write: "python".capitalize().
Syntax
String.capitalize()
Code example 1
my_str = "foo bar"
result = my_str.capitalize()
print(result)
Output
Foo bar
This code example capitalizes the first letter of the string "foo bar". The result is "Foo bar".
Code example 2
my_str = "proGrAmming is Fun"
result = my_str.capitalize()
print(result)
Output
Programming is fun
The capitalize() function will convert the first letter of the string to Uppercase and all the other letters will be lowercase.
Python has a built-in function called upper() which converts a string into upper case. There is also a string index that can be used to access individual characters in a string. By combining these two features, it is possible to capitalize the first letter of a string. We will understand it using below code example.
Syntax
input_str[0].upper() + input_str[1:]
Code example
my_str = "devsheet is for programmers"
result = my_str[0].upper() + my_str[1:]
print(result)
Output
Devsheet is for programmers
This code example is using the string method upper() to make the first letter of the string uppercase, and then concatenates the rest of the string to it.
The String.title() function in Python is used to capitalize the first letter of each word in a string. This is a built-in function, so you don't need to import anything to use it.
Syntax
String.title()
Code example
question = "how to make pizza"
result = question.title()
print(result)
# Output
# How To Make Pizza
Output
How To Make Pizza
The code example above shows how to make a string title() case using the title method. The title() method returns a string with each word capitalized.
The capwords() function of the string module in Python can be used to capitalize each word in a string. This is useful when creating Headings or titles.
Python's string module provides a capwords() function which takes a string as an argument and returns a capitalized version of the string where each word is capitalized and all other characters are lowercase. This function is useful for creating readable, title-like strings.
Syntax
import string
string.capwords(input_str)
Code example
import string
my_str = "making the world a bEtter place"
result = string.capwords(my_str)
print(result)
Output
Making The World A Better Place
In the above code example
0 Comments