Error trying to print the first occurrence of a duplicate character in a string using Python 3.6

I am writing a simple program to replace duplicate characters in a string with *(asterisk). But here I can print the first occurrence of a repeating character in a string, but not other occurrences.

For example, if my input Google , my output should be Go**le.

I can replace characters that repeat with an asterisk, but just can't find a way to print the first occurrence of the character. In other words, my conclusion is now ****le.

Take a look at my code for this: Python3

s = 'Google'
s = s.lower()
for i in s:
    if s.count(i)>1:
        s = s.replace(i,'*')
print(s)

Can someone tell me what needs to be done to get the desired result?

+4
3

replace char. , , , JUST ( ).

, , ''.join() .

Set, , .

:

s = 'Google'
seen = set()
new_string = []

for c in s:
    if c.lower() in seen:
        new_string.append('*')
    else:
        new_string.append(c)
        seen.add(c.lower())

new_string = ''.join(new_string)
print(new_string)
Go**le
+2

:

n- . :

s = s[:position] + '*' + s[position+1:]

:

def find_nth(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+len(needle))
        n -= 1
    return start

s = 'Google'
s_lower = s.lower()

for c in s_lower:
    if s_lower.count(c) > 1:
        position = find_nth(s_lower, c, 2)
        s = s[:position] + '*' + s[position+1:]
print(s)

Runnable link: https://repl.it/Mc4U/4


Regex :

import re

s = 'Google'

s_lower = s.lower()

for c in s_lower:
    if s_lower.count(c) > 1:
        position = [m.start() for m in re.finditer(c, s_lower)][1]
        s = s[:position] + '*' + s[position+1:]

print(s)

Runnable link: https://repl.it/Mc4U/3

+2

? ( , , ), - :

#!/usr/bin/env python
# -*- coding: utf-8 -*-

inputstring = 'Google'.lower()
outputstring = ''.join(
    [char if inputstring.find(char, 0, index) == -1 else '*'
    for index, char in enumerate(inputstring)])
print(outputstring)

go**le.

Hope this helps!

( edited to use '*' as a replacement character instead of '#')

+2
source

Source: https://habr.com/ru/post/1687479/


All Articles