Home > OS >  Change selected characters in a string using loop
Change selected characters in a string using loop

Time:12-21

I'm writing a function to change the letter case of even letters in a string (spaces/punctuation is ignored). ie, from "Abcd. Efgh.. Ijkl!" to "abCd. efGh.. IJkL!"

My code only changes the first letter. Initially I thought my issue was the replace() function so I switched to the .append() function instead but the result still remains the same: ['abcd. Efgh.. Ijkl!']

How can I change the code to capture the result of each loop?

def mock(string):
    new_string=[]
    new_letter=""
    for letter in string[::2]:
        if letter.islower():
            new_letter= letter.upper()
            new_string.append(string.replace(letter,new_letter))
            
        elif letter.isupper():
            new_letter= letter.lower()
            new_string.append(string.replace(letter,new_letter))

        return new_string

print(mock("Abcd. Efgh.. Ijkl!")) 

CodePudding user response:

You should use either .replace() or .append() but .replace() will replace all occurrences (not just even ones). You can rewrite your code as:

def mock(string):
    new_string = []
    for index, letter in enumerate(string):
        new_letter = letter
        if index % 2 == 0:
            if letter.islower():
                new_letter= letter.upper()
            elif letter.isupper():
                new_letter= letter.lower()
        new_string.append(new_letter)
    return "".join(new_string)

You could also use a list comprehension. A single line implementation would be

return "".join(s if i%2 else s.swapcase() for i, s in enumerate(string))
  • Related