Home > Net >  Replace second occurence of every character in a string, Python
Replace second occurence of every character in a string, Python

Time:05-11

I want to replace every second occurence of a character from only a string as input. Using only the .replace method.

For example:

input: asdasdasdasd

output should be: asdASDasdasd

def main(string):
   for char in string:
      string.replace(char, char.upper())
   return string

Im relatively new to Python and I can't wrap my head around what to do.

CodePudding user response:

Alternatively, you can use a dictionary and make the second occurrence of each character to uppercase:

def upper_case_second_occurrence(s):
    d = {}
    s = list(s)
    for i, c in enumerate(s):
        d[c] = d.get(c, 0)   1
        if d[c] == 2:
            s[i] = c.upper()
    return "".join(s)


if __name__ == "__main__":
    print(upper_case_second_occurrence("aaa"))
    print(upper_case_second_occurrence("aaaaaa"))
    print(upper_case_second_occurrence("asdasdasdasd"))

Output:

aAa
aAaaaa
asdASDasdasd

CodePudding user response:

Try this one:

def main(s):
    l = []
    string = ''
    y = True
    for a in s:
        if a in l and y:
            string =a.upper()
            l.remove(a)
            if not len(l):
                l = ''
            continue
        try:
            l.append(a)
        except AttributeError:
            y = False
        string =a
    return(string)

print(main('asdasdasdasd')) # → asdASDasdasd
print(main('aaa')) # → aAa
print(main('aaaaa')) # → aAaaa
print(main('AAA') # → AAA

CodePudding user response:

Try using .count():

def main(string):
    new_string = ''
    for char in string:
        if new_string.lower().count(char) == 1: # This line checks if the count of char is 1 or not. If yes, then it appends the uppercase letter of char
            new_string  = char.upper()
        else:
            new_string  = char
    return new_string

Output:

main('asdasdasdasd')
'asdASDasdasd'
main('aaaaaa')
'aAaaaa'
main('aaa')
'aAa'
  • Related