python-3.xlistkeywordenumeratecountries

Capitalize a character Before and After Nth character in a string in a Python list


Here is my code I am trying uppercase letters before and after a specific letter in a list. Uppercase any letter before and after uppercase the previous and next letters that come before and after each "z" in a capital city. All other letters are lowercase. All cities that contain that letter will be stored in a list and returned. If I could get some input that would be great. Also if I need to change the code completely please let me know of other ways. I am new to this any input would be appreciated. Thanks

lst = ['brazzaville', 'zagreb', 'vaduz']

lst2 = []
for wrd in lst:
    newwrd = ''
    for ltr in wrd:
        if ltr in 'ua':
            newwrd += ltr.capitalize()
        else:
            newwrd += ltr

    lst2.append(newwrd)
print(lst2)

I keep getting this:

['brAzzAville', 'zAgreb', 'vAdUz']

But I need this:

['brAzzAville', 'zAgreb', 'vadUz']

Solution

  • The following strategy consists of iterating through the word and replacing the letters at index-1 and index+1 of z (if they exist) with upper case letters:

    lst2 = []
    for wrd in lst:
        wrd = wrd.lower()
        for idx, letter in enumerate(wrd):
            if letter == 'z':
                if idx-1 > 0 and wrd[idx - 1] != 'z':
                    wrd = wrd.replace(wrd[idx - 1], wrd[idx - 1].upper())
                if idx+1 < len(wrd) and wrd[idx + 1] != 'z':
                    wrd = wrd.replace(wrd[idx + 1], wrd[idx + 1].upper())
        if "z" in wrd:
            lst2.append(wrd)
    
    print(lst2)
    #['brAzzAville', 'zAgreb', 'vadUz']