13

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

Community
  • 1
  • 1
Trojosh
  • 545
  • 1
  • 5
  • 15

7 Answers7

21

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

def capitalize_nth(s, n):
    return s[:n].lower() + s[n:].capitalize()
jfs
  • 374,366
  • 172
  • 933
  • 1,594
14
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:]])
icktoofay
  • 122,243
  • 18
  • 242
  • 228
  • Here is some more information regarding string concatenation in python https://stackoverflow.com/questions/12169839/which-is-the-preferred-way-to-concatenate-a-string-in-python – casol Jan 03 '19 at 20:46
  • 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). – jfs May 02 '19 at 19:29
1
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.

cppcoder
  • 20,990
  • 6
  • 49
  • 78
0

I know it's an old topic but this might be useful to someone in the future:

def myfunc(str, nth):
new_str = '' #empty string to hold new modified string
for i,l in enumerate(str): # enumerate returns both, index numbers and objects
    if i % nth == 0: # if index number % nth == 0 (even number)
        new_str += l.upper() # add an upper cased letter to the new_str
    else: # if index number nth
        new_str += l # add the other letters to new_str as they are
return new_str # returns the string new_str
ZiP
  • 91
  • 1
  • 3
0

A simplified answer would be:

    def make_nth_letter_capital(word, n):
        return word[:n].capitalize() + word[n:].capitalize()
0
def capitalize_n(string, n):
return string[:n] + string[n].capitalize() + string[n+1:]

This works perfect

0

You can use:

def capitalize_nth(text, pos):
    before_nth = text[:pos]
    n = text[pos].upper()
    new_pos = pos+1
    after_nth = text[new_pos:]
    word = before_nth + n + after_nth
    print(word)

capitalize_nth('McDonalds', 6)

The outcome is:

'McDonaLds'

I think this is the simplest among every answer up there...