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
Keep in mind that swapcase
will invert the case whether it is lower or upper.
I used this just to show an alternate way.
Author by
Trojosh
Updated on September 15, 2020Comments
-
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 likemake_nth_letter_cap(str, n)
. -
cppcoder about 11 yearsI added a note below my answer
-
casol over 5 yearsHere is some more information regarding string concatenation in python stackoverflow.com/questions/12169839/…
-
jfs about 5 yearsin 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])
ora+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 almost 5 yearsCould you add short explanation what this code does