Search code examples
pythonstringuppercase

Capitalize the last two letters in a string


My attempt:

location = "new orleans, la"
location = location[:-1].upper()

The last letter gets cut off. I just want the state (2-letter abbreviation) capitalized.


Solution

  • This code preserves all but the last two characters in their original state. To that, it appends the final two characters in upper case.

    location = "new orleans, la"
    location = location[0:-2] + location[-2:].upper()
    

    You got cut off because that's exactly what you told it to do: take all characters up to -- but not including -- the last one, convert them all to upper-case, and make that the new value of location.

    Result:

    'new orleans, LA'