Renz Jan Paolo Cortez
Renz Jan Paolo Cortez

Reputation: 33

How to change only a specific letter at a specific index in a string to uppercase/lowercase

Here is the code:

def upper_every_nth (s, n):
    i = 0
    while len (s) > (i * (0 + n)) :
        character = s[i * (0 + n)]
        s = s.replace(character, character.upper(), 1)
        i = i + 1
    return (s)

I want it to return a string that is identical to s except that every nth character (starting at position 0) is uppercase.

>>> upper_every_nth("cat", 2)
'CaT'
>>> upper_every_nth("hat", 3)
'Hat'

The problem is I cannot use the.replace method since it replaces all the occurrences of that letter in a string if not, only the first occurrence.

So let's say the string is 'deer'. I want to convert the second occurrence of 'e' to upper case. But with .replace method, it is either I get 'dEEr' or 'dEer'.

Upvotes: 3

Views: 6942

Answers (4)

deva
deva

Reputation: 1

i = 0
word = ''
while len(s) > i:
    if i % n == 0:
        word = word + s[i].upper()
        i +=1
    else: 
        word = word + s[i]
        i +=1
return (word)

Upvotes: 0

user1277476
user1277476

Reputation: 2909

In 2.x or 3.x, use a list of single-character strings. In 3.x, you can also use a bytearray:

#!/usr/local/cpython-3.4/bin/python3

'''Demonstrate capitalizing every nth letter of a word'''


def upper_every_nth_via_list(word, number):
    '''Capitalize every nth letter of a word'''
    new_word = []
    for index, value in enumerate(word):
        if index % number == 0:
            new_word.append(value.upper())
        else:
            new_word.append(value)
    return ''.join(new_word)


def upper(character):
    '''convert character to uppercase if lowercase'''
    if ord(b'a') <= character <= ord(b'z'):
        character += ord(b'A') - ord(b'a')
    return character


def upper_every_nth_via_bytearray(word, number):
    '''Capitalize every nth letter of a word using a 3.x byte string'''
    new_word = word[:]
    for index, value in enumerate(new_word):
        if index % number == 0:
            new_word[index] = upper(value)
    return new_word


def main():
    '''Main function'''
    string = upper_every_nth_via_list('abcdefgabcdefggfedcba', 3)
    print('{}\n'.format(string))

    input_bytearray = bytearray(b'abcdefgabcdefggfedcba')
    bytearray_string = upper_every_nth_via_bytearray(input_bytearray, 3)
    print('{}\n'.format(bytearray_string))


main()

Upvotes: 0

NPE
NPE

Reputation: 500157

You need to work with indices. Here is how you can replace the k-th character of string s with character ch:

s = s[:k] + ch + s[k+1:]

To understand how s[:k] and s[k+1:] work, have a read of Explain Python's slice notation. The + simply concatenates several strings together.

Upvotes: 4

Cory Kramer
Cory Kramer

Reputation: 117856

def upper_every_nth(word, n):
    return ''.join(value if index%n else value.upper() for index, value in enumerate(word))

Testing

>>> upper_every_nth('dictionary', 3)
'DicTioNarY'

To break this up more explicitly, you can use a for loop

def upper_every_nth(word, n):
    newWord = ''
    for index, value in enumerate(word):
        if index % n == 0:
            newWord += value.upper()
        else:
            newWord += value
    return newWord

Upvotes: 0

Related Questions