Selective casing in strings in Python
In this article, you will learn about how to change the casing of a particular letter in the string in Python. There are quite a few ways to do it. We can directly use the inbuilt function and simply write one. It explore both ways.
First, we will write to change a lower case letter to upper case letter then write a generalized code.
Method 1
orig_str="Code speedy"
j=str(input("enter the letter"))
orig_lis=list(orig_str)
for i in range(len(orig_lis)):
if orig_lis[i]==j:
orig_lis[i]=j.upper()
print("".join(i for i in orig_lis))Output:
enter the string : s Code Speedy
Here we searched for the letters in the string then change it in the corresponding element in the list.
Method 2
orig_str="Code speedy"
j=str(input("enter the string"))
orig_lis=list(orig_str)
for index,value in enumerate(orig_lis):
if(value==j):
orig_lis[index]=j.upper()
print("".join(i for i in orig_lis))Output:
enter the string : s Code Speedy
Here we followed the same approach as Method 1 but used enumerate function instead of pointing to list element with index.
Method 3
orig_str="Code speedy"
j=str(input("enter the letter to change the casing"))
cas=str(input("specify upper or lower casing"))
orig_lis=list(orig_str)
for index,value in enumerate(orig_lis):
if(value==j and cas=="upper" ):
orig_lis[index]=j.upper()
elif(value==j and cas=="lower"):
orig_lis[index]=j.lower()
print("".join(i for i in orig_lis))Output:
enter the letter to change the casing: s specify upper or lower casing: upper Code Speedy
That’s it guys here are the methods to selectively change the casing of letter in a string. If you could come up with more efficient methods do mention in comments.
Leave a Reply