How to change identical operators in Python list of strings by including different numbers or subscripts?

Viewed 63

I have a list of strings in Python, containing alphabets and operators as follows:

['a', '+', 'b', 'd', '+', 'e', 'g', '*', 'h', '/', '-', '/'].

I am trying to use Python to rename the first '+' as potentially '+1' (where the '1' next to '+' could be a subscript) and the second '+' as '+2' to distinguish between the two '+' operators. And so on for the other operators as well. Also, for similar other bigger examples containing multiple '+', '-', '*', '/', '<', '>', etc.

For example, in the above list of strings, the modification would result to the desired output I wish to achieve:

['a', '+1', 'b', 'd', '+2', 'e', 'g', '*1', 'h', '/1', '-1', '/2'].

I was trying to use a for loop to find each operator and replace it by the numbers, but haven't been successful. Your help would be highly appreciated.

2 Answers

We can use a dictionary to store the current amount of special characters in your code:

specChars = {'+':0, '-':0, '*':0, '/':0, '<':0, '>':0}

Now, we can iterate through your list and update the elements appropriately:

specChars = {'+':0, '-':0, '*':0, '/':0, '<':0, '>':0}

lst = ['a', '+', 'b', 'd', '+', 'e', 'g', '*', 'h', '/', '-', '/']

for i in range(len(lst)):
  if lst[i] in specChars:
    specChars[lst[i]] += 1
    lst[i] = lst[i] + str(specChars[lst[i]])

print(lst)

Output:

['a', '+1', 'b', 'd', '+2', 'e', 'g', '*1', 'h', '/1', '-1', '/2']

This loop works by iterating through our list of characters, lst. If the character is a special character, we increase the corresponding value in specChars. Then, we concatenate the frequency of that character.

I hope this helped! Please let me know if you need any further clarifications or details :)

This should work

def fun(arr):
    operator = {
    '+': 1,
    '-': 1,
    '*': 1,
    '/': 1,
    '<': 1,
    '>': 1
    }

    res = []

    for i in arr:
        if i in operator:
            res.append(i + str(operator[i]))
            operator[i] += 1
        else:
            res.append(i)

    return res

print(fun(['a', '+', 'b', 'd', '+', 'e', 'g', '*', 'h', '/', '-', '/']))
Related