-3

I was looking for some staff in forum, but everything looks pretty complicated or it's making only first letter big and others small and etc. Is there a way to change only first letter to uppercase ? Something like :

test = 'someThing'
anotherTest = test(it will become 'SomeThing')
Rakesh
  • 81,458
  • 17
  • 76
  • 113
Vlad
  • 77
  • 6

1 Answers1

1

'someThing'.title() will downcase the rest of the word, so you need to target the first letter only:

>>> var = 'someThing'
>>> print(var.title())
Something
>>> print(var[0].title() + var[1:])
SomeThing

Looks complex, I know, but there's no default string operator for this. You can always wrap it in a simple function:

def CamelCase(s):
    return s[:1].title() + s[1:]

(By using the range s[:1], I avoid an error on the empty string.)

alexis
  • 48,685
  • 16
  • 101
  • 161
  • 1
    `.upper()` might be clearer – Chris_Rands Mar 27 '18 at 08:07
  • I think that's down to individual preference, Chris. For me, using `title()` on a single letter telegraphs the intent of the whole construction, so I consider that clearer. – alexis Mar 27 '18 at 08:10
  • agree it's subjective, but to me, `.upper()` is more well known and sufficient, if you want to show intent, `.capitalize()` would seem clearer that `.title()` – Chris_Rands Mar 27 '18 at 08:14
  • I specifically chose `title()` over `capitalize()` because it's the one I've seen more often in my experience. I rest my case :-) – alexis Mar 27 '18 at 09:27