Python How to capitalize nth letter of a string

39,592

Solution 1

Capitalize n-th character and lowercase the rest as capitalize() does:

def capitalize_nth(s, n):
    return s[:n].lower() + s[n:].capitalize()

Solution 2

my_string[:n] + my_string[n].upper() + my_string[n + 1:]

Or a more efficient version that isn't a Schlemiel the Painter's algorithm:

''.join([my_string[:n], my_string[n].upper(), my_string[n + 1:]])

Solution 3

x = "string"
y = x[:3] + x[3].swapcase() + x[4:]  

Output

strIng  

Code

Keep in mind that swapcase will invert the case whether it is lower or upper.
I used this just to show an alternate way.

Share:
39,592
Trojosh
Author by

Trojosh

Updated on September 15, 2020

Comments

  • Trojosh
    Trojosh over 3 years

    I tried this: Capitalize a string. Can anybody provide a simple script/snippet for guideline?

    Python documentation has capitalize() function which makes first letter capital. I want something like make_nth_letter_cap(str, n).

  • cppcoder
    cppcoder about 11 years
    I added a note below my answer
  • casol
    casol over 5 years
    Here is some more information regarding string concatenation in python stackoverflow.com/questions/12169839/…
  • jfs
    jfs about 5 years
    in your case N=3 and therefore we can't be sure what implementation O(N) or O(N*N) would be more "efficient" (for such a small N). I don't know what is more efficient ''.join([a, b, c]) or a+b+c (or is it even worth it to worry about the time it takes to concatenate a couple of string relative to other parts in a codebase).
  • Cray
    Cray almost 5 years
    Could you add short explanation what this code does