DEV Community

Cover image for I kept playing with my code and made a function to uppercase a letter instance in a string.
wormondeck
wormondeck

Posted on

I kept playing with my code and made a function to uppercase a letter instance in a string.

I was messing around with the .upper() method in Codecademy and stumbled upon the forum section where a few devs were asking about uppercasing other letters in a string aside from the first. So I started testing different code and figured out a way to uppercase a specific letter. Here's the forum that inspired me to investigate:

Image description



def upper_that_letter(some_str):
  upper_letter = ""
  for letter in some_str:
    if letter == "o":
      upper_letter = letter.upper()
      rep_letter_o = some_str.replace("o", upper_letter) 
  return rep_letter_o

print(upper_that_letter("Hola Mundo"))


Enter fullscreen mode Exit fullscreen mode

The part mentioning coming up with your own function gave me my first line of code to work with, I realized a string is immutable so to begin I created an empty string variable and since strings work similar to lists its only right to iterate for a specific letter, hello for loop. I then added a condition specifying if that letter is in our case: "o" then we would use the upper() method on it and place it in a variable we would call upper_letter.

At this point I got stuck and tried different scenarios to include the string passed in when calling the function but only got the letter "O"s returned in caps. Then I thought about the replace() method! I realized the method replace() takes two arguments, the string to search and replace as well as the string to replace the old value with. There is also a third argument specifying how many occurrences of the old value you want to replace (this ones a plus!). This method made it all connect for my function.

Now to put our replace() method in to play I used it on the some_str parameter with "o" as the first argument to be replaced and the upper_letter variable as its new replacement. Now we shall return our variable replace_letter_o, and call our function with "Hola Mundo" and get our desired output of "HOla MundO"!

I'm sure there's been many ways of getting this done but I wanted to share this not only to provide a solution but most importantly to show how understanding the tools available to you and trying different things on your own can help you find ways to become better at problem solving and enjoying coding!

Top comments (0)