Is there a function to replace a single character in a string in an nested list in python?

Question:

I’ve been stumped on this problem for the last few hours. In this program:

It starts with a list in this format:

[[“no1/0~1~2~3~4~5~6], [“no2/7~8~9~10~11~12~13] …etc]

Is there a way to easily increment the first number in all of them to different one resulting in a string that looks like this?

[[“no1/1~1~2~3~4~5~6], [“no2/8~8~9~10~11~12~13”] …etc]

I have tried an extremely complicated method of splitting the strings such as:

for cur_year in range(simulation_years):
    reader_testsubjects = []
    for subjectlen in range(len(testsubjects)): reader_testsubjects.append(testsubjects[subjectlen].split("/"))
    reader_attributes = []
    for attributelen in range(len(reader_testsubjects)): reader_attributes.append((reader_testsubjects[attributelen][1]).split("~"))
    for agechangelen in range(len(reader_attributes)):
        reader_attributes[agechangelen][0].replace(reader_attributes[agechangelen][0], str(int(reader_attributes[agechangelen][0]) + 1))
        print(str(int(reader_attributes[agechangelen][0]) + 1))
        # weird bug with only increasing once in the entire year loop. fix later :(
    print(f"Year: {cur_year}: {reader_attributes[0][0]}")

But that has not been working since it only changes it once, instead of changing it everytime the loop repeats. Can someone help me on this, I’ve been stumped on this for a few hours. Thanks!

I have also tried using .replace, but it cannot replace one item in a nested list.

Asked By: RinUnderscore

||

Answers:

You can try to using re module:

import re

lst  = [["no1/0~1~2~3~4~5~6"], ["no2/7~8~9~10~11~12~13"]]

lst = [[re.sub(r'(?<=/)d+', lambda g: str(int(g.group(0))+1), s) for s in l] for l in lst]
print(lst)

Prints:

[['no1/1~1~2~3~4~5~6'], ['no2/8~8~9~10~11~12~13']]
Answered By: Andrej Kesely