11

I'm trying to write a single line statement that assigns the value of a string to a variable after having ONLY the first letter capitalized, and all other letters left unchanged.

Example, if the string being used were:

myString = 'tHatTimeIAteMyPANTS'

Then the statement should result in another variable such as myString2 equal to:

myString2 = 'THatTimeIAteMyPANTS'
bad_coder
  • 11,289
  • 20
  • 44
  • 72
Oliver Vakomies
  • 133
  • 1
  • 1
  • 4

2 Answers2

25

Like this:

myString= myString[:1].upper() + myString[1:]
print myString
bad_coder
  • 11,289
  • 20
  • 44
  • 72
Ukimiku
  • 608
  • 1
  • 6
  • 13
8

Like Barmar said, you can just capitalize the first character and concatenate it with the remainder of the string.

myString = 'tHatTimeIAteMyPANTS'
newString = "%s%s" % (myString[0].upper(), myString[1:])
print(newString)  # THatTimeIAteMyPANTS
bad_coder
  • 11,289
  • 20
  • 44
  • 72
chatton
  • 596
  • 1
  • 3
  • 8
  • 12
    It's easier to just do `newString = myString[:1].upper() + myString[1:]` and clearer. Doing `:1` and not `0` to prevent exceptions in case the string is empty – Artemis Nov 06 '16 at 20:37
  • Yes good point, I didn't think about empty strings. – chatton Nov 06 '16 at 20:41