Replace letters in list item to numbers

Viewed 703

I am new here and also fairly new to programming. I recently started learning Python to learn how to automate processes in my everyday tasks.

I am working with comparing 2 lists that I created from converting 2 columns from 2 Excel files into lists. The lists mainly contain numbers, but some items contain both integers and letters, and this I believe results in becoming a string rather than an integer. I would like to convert the letters into numbers to have a list of integers to be able to manipulate, compare, etc. Is there any way I can do this? I have been using openpyxl to access my Excel files. Below is an example of what I would like to do.

Ex: input

list1 = [8635, 6227, '8651FRT', '8651BK','8295INSERT', 8295]

output

newlist1 = [8635, 6227, 865101, 865102,829503, 8295]

I would like to replace 'FRT' with 01, 'BK' with 02, and 'INSERT' with 03. I would really appreciate the help. Thanks.

6 Answers

one way, is to define a dict with values to replace followed by re.sub to extract & replace the values.

import re

replace = {"FRT": "01", 'BK': "02", 'INSERT': "03"}

list1 = [8635, 6227, '8651FRT', '8651BK', '8295INSERT', 8295]

print(
    [int(re.sub(r"([A-Za-z]+)",
            lambda x: replace.get(x.group(1), ""), str(x))) for x in list1]
)
[8635, 6227, 865101, 865102, 829503, 8295]

You can use:

newlist1 = [int(str(item).replace('FRT', '01').replace('BK', '02').replace('INSERT','03')) for item in list1]

All the information needed was found using help(str) if you want more.

You can write a function to replace one item (I can't see an easy shortcut for this), then you can loop over it in a list comprehension.

import re

mappings = {'FRT': '01', 'BK': '02', 'INSERT': '03'}

def replace(val):
    
    if isinstance(val, int):
        return val
    
    m = re.match('(\d+)(\D+)$', val)
    if m:
        key = m.group(2)
        if key in mappings:
            return int(m.group(1) + mappings[key])

    raise ValueError('could not do replacement for {}'.format(val))


list1 = [8635, 6227, '8651FRT', '8651BK','8295INSERT', 8295]

print([replace(x) for x in list1])

gives:

[8635, 6227, 865101, 865102, 829503, 8295]

Its not the best example. You could do it faster and better. But I guess this is understandable how you could aproach it. :)

list1 = [8635, 6227, '8651FRT', '8651BK','8295INSERT', 8295]
newlist = []
# Check every item in list
for item in list1:
  # If its a integer, add to newlist
  if isinstance(item, int):
    newlist.append(item)
    continue
  # Else check and replace
  if 'FRT' in item:
    item = item.replace('FRT', '01')


 # Check other exception here
  
   newlist.append(int(item))

You can iterate over your list of values. When you come across a non-integer number, you can strip off the letters, and append an incrementing counter to it. You then add this counter to a mapping dict to make sure you use the same value each time. This shouldn't require any pre-work or mapping. This does assume the letters are at the end or are after your numbers.

import re
list1 = [8635, 6227, '8651FRT', '8651BK','8295INSERT', 8295,8295 , '8295INSERT', '8651BK' , '8295INSERT', '8651BK',6227 , ]
mapping = {}
counter_ = 1
output_list = []
for x in list1:
    if isinstance(x, int):
        output_list.append(x)
        pass
    else:
        output = re.split(r'(\d+)', x)
        try:
            val = mapping[output[2]]
            output[2] = val
            output_list.append(''.join(output[1:]))
        except:
            mapping[output[2]] = '0'+str(counter_)
            output[2] = '0'+str(counter_)
            output_list.append(''.join(output[1:]))
        counter_ += 1

newlist = [int(x) for x in output_list]

You can replace the string with the count of a variable. Maybe you are looking for this.

list1 = [8635, 6227, '8651FRT', '8651BK','8295INSERT', 8295]
mod = []
c = 1

for val in list1:
    if (str(val).isnumeric()): mod.append(val)
    else:
        n = len(val)
        for i in range(n):
            if (not val[i].isnumeric()):
                if (c<10): 
                    mod.append(int(val[0:i]+'0'+str(c)))
                    c+=1
                    break
                else: 
                    mod.append(int(val[0:i]+str(c)))
                    c+=1
                    break

print(mod)

Thank you

Related