Index capitalization

Question:

I want to create a function that capitalizes a string according to the array that is provided. My current function takes in 2 arguments: the string you want to change and an array which would correspond to the letters you want to change. My function looks like so:

def capitalize(s, ind):
    for i in ind:
        try:
            s = s.replace(s[i], s[i].upper())
        except IndexError:
            print("Sorry, index is not range!")
    return s

This function seemed to work at first, when I tried a few examples such as:

capitalize("abc",[1,2])
#Output: aBC

However, I cannot work out why this example fails:

capitalize("abracadabra",[2,6,9,10])
#Output: AbRAcADAbRA - should be abRAcADAbRA

Why is my first letter suddenly becoming capitalized? Any help would be deeply appreciated.

Asked By: mf94

||

Answers:

str.replace replaces the first match it finds. So s.replace(s[10], s[10].upper()) (which is an a), won’t replace the a at index 10, but the first a it finds in the string.

Instead, convert your string to a list:

import sys

def capitalize(s, ind):
    split_s = list(s)
    for i in ind:
        try:
            split_s[i] = split_s[i].upper()
        except IndexError:
            print(f"Sorry, index is not in range! ({i})", file=sys.stderr)
    return "".join(split_s)

print(capitalize("abracadabra",[2,6,9,10,50]))

Output:

Sorry, index is not in range! (50)

abRacaDabRA

Answered By: Sean Breckenridge
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.