-1

I can't wrap my head around this, I need to re.sub multiple times looking for different patterns. The below script works but it's definitely not pythonic.

I thought I could use a dictionary where the first number is the key, and value would be what it gets replaced by.

lines contains rows of data like "abc/3/def/ghi/jkl/mno//.

Any pointers in how I can clean this code? I'm after an output that replaces the nominal 3 in the above example to Size-3.

  for line in lines:
    tokens = line.split(delimiter)
    tokens = [re.sub('^4$', 'Size-4', token) for token in tokens]
    tokens = [re.sub('^5$', 'Size-5', token) for token in tokens]
    tokens = [re.sub('^6$', 'Size-6', token) for token in tokens]
    tokens = [re.sub('^7$', 'Size-7', token) for token in tokens]
    tokens = [re.sub('^8$', 'Size-8', token) for token in tokens]
    tokens = [re.sub('^9$', 'Size-9', token) for token in tokens]
    tokens = [re.sub('^10$', 'Size-10', token) for token in tokens]
    tokens = [re.sub('^12$', 'Size-12', token) for token in tokens]
    tokens = [re.sub('^14$', 'Size-14', token) for token in tokens]
    tokens = [re.sub('^16$', 'Size-16', token) for token in tokens]
    print(tokens)
  • https://codereview.stackexchange.com/ – 0m3r May 16 '22 at 20:44
  • What does `lines` look like? What is your expected output? Please read [ask] and the [question checklist](//meta.stackoverflow.com/q/260648/843953) and provide a [mre] – Pranav Hosangadi May 16 '22 at 20:45
  • 1
    @PranavHosangadi edited question. I'm looking to use a dictionary for the `re.sub()` – Chaotic.Python May 16 '22 at 20:49
  • What about `tokens = [f'Size-{token}' if token.isdigit() else token for token in tokens]`? – Wiktor Stribiżew May 16 '22 at 20:49
  • Your regexes don't look for size `3`. Do you want to replace _any_ items that are entirely numeric, or do you have certain sizes that you are looking for? Also if your size is going to be in a fixed, known column then you can just replace that column instead of trying to replace all columns – Pranav Hosangadi May 16 '22 at 20:49
  • @PranavHosangadi Ahh, things I havn't thought of. No I'd like the regexes to only look for a single instance of the mentioned numerics. So `5`, `6` etc. and replce with what's above. – Chaotic.Python May 16 '22 at 20:51

0 Answers0