Search code examples
pythonstringuppercase

How to Make 1st Letter of String Upperase with upper() - PYTHON


I am trying to change the first letter of the string so that it is upper case. I know it is posible to use capitalize() or title() but I am just testing things out and wanted to know how I could do the same thing with upper(). The code I've tried comes up with error message: 'TypeError: newS must be a string on line 10'. Any suggestions would be very much appreciated!

def uppercase(string):
  string = string.replace(string[0],string[0].upper) 
  return string
print uppercase("hello")

Solution

  • You missed () while calling upper which is a method:

    def uppercase(string):
      string = string.replace(string[0],string[0].upper(), 1) 
      return string
    
    print(uppercase("hello"))
    

    Also, as deceze pointed the replace() based approach will fail as is and you can use the optional maxreplace parameter to 1 to only replace the first occurrence.