Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python How to capitalize nth letter of a string

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).

like image 580
Trojosh Avatar asked Apr 07 '13 01:04

Trojosh


3 Answers

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

def capitalize_nth(s, n):
    return s[:n].lower() + s[n:].capitalize()
like image 90
jfs Avatar answered Oct 20 '22 03:10

jfs


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:]])
like image 32
icktoofay Avatar answered Oct 20 '22 05:10

icktoofay


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.

like image 37
cppcoder Avatar answered Oct 20 '22 05:10

cppcoder