Skip to content
Advertisement

Add a character to a specific duplicate string

I’m trying to add a character to a specific duplicate string, like in the following situation:

nomes_comp = ['Fulano A', 'Beltrano B', 'Fulano A']

So I have duplicate items on my list; I would like to add another character in one of the duplicate items, hoping to get the following output:

nomes_comp = ['Fulano A', 'Beltrano B', 'Fulano A1']

I’m trying this way, but it’s not working:

for nome in zip(nomes[0], nomes[1]):
   nomes_comp.append(nome[0] + ' ' + nome[1])

Advertisement

Answer

Use a dictionary (or a collections.defaultdict) to keep track of how many occurrences you’ve found.

nomes_comp = ['Fulano A', 'Beltrano B', 'Fulano A']

count_d = dict()

for i, n in enumerate(nomes_comp):
    c = count_d.get(n, 0)
    count_d[n] = c + 1
    if c:
        nomes_comp[i] = n + str(c)

After you do this, the original nomes_comp is modified to:

['Fulano A', 'Beltrano B', 'Fulano A1']
Advertisement