To convert the first letter of a string to lowercase in Python, you can use string slicing and the lower() function.
string = "EXAMPLE"
first_lowercase = string[0].lower() + string[1:]
print(first_lowercase)
#Output:
eXAMPLE
When working with strings in Python, the ability to be able to change and manipulate the values of those strings can be very valuable.
One such change is making the first letter of a string lowercase.
To convert the first letter of a string to lowercase, you can use string slicing and the Python lower() function.
First, we get the first letter of a string and then use the lower() function to make it lowercase.
Then, you get the string starting at the second character to the end and concatenate these two pieces together.
Below is an example showing how to make the first letter of a string lowercase with Python.
string = "EXAMPLE"
first_lowercase = string[0].lower() + string[1:]
print(first_lowercase)
#Output:
eXAMPLE
How to Make Specific Character Lowercase in String Using Python
If you want to make a specific character lowercase in a string using Python, we can take the example above and make a slight adjustment.
For example, if you want to make the fourth character of a string lowercase, then we need to get a slice of the first three characters, the fourth character, and a slice of the characters after the fourth character.
After making the fourth character lowercase with the Python lower() function, we then concatenate the three pieces as shown below.
string = "EXAMPLE"
fourth_lowercase = string[:3] + string[3].lower() + string[4:]
print(fourth_lowercase)
#Output:
EXAmPLE
A function which makes the nth letter lowercase is shown below.
def lowercase_letter(string, n):
return string[:n-1] + string[n-1].lower() + string[n:]
string_example = "EXAMPLE"
print(lowercase_letter(string_example, 3))
#Output:
EXaMPLE
How to Make the First n Characters of a String Lowercase with Python
If you want to make the first n characters of a string lowercase, you can get the slice of the first n characters, convert it to lowercase, and add it to the slice of characters after the nth position.
Below shows a simple example of how you can make the first 3 characters of a string lowercase with Python.
string = "EXAMPLE"
first_three_lowercase = string[:3].lower() + string[3:]
print(first_three_lowercase)
#Output:
exaMPLE
A function which makes the first n characters lowercase is shown below.
def first_n_lowercase(string,n):
return string[:n-1].lower() + string[n-1:]
string_example = "EXAMPLE"
print(first_n_lowercase(string_example, 3))
#Output:
exAMPLE
Hopefully this article has been useful for you to learn how to make the first letter of a string lowercase in Python.