Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python good way to manipulate string depending on an input variable

sorry if the title is a bit vague. I will try to explain it now.
My scenario is the following:
I am reading a cfg-file and receive a dictionary for each section. So, for example:
Config-File:

[General]
parameter1="Param1"
parameter2="Param2"

[FileList]
file001="file1.txt"
file002="file2.txt" ......

Now, let’s focus on the FileList-section, which is saved as a dictionary. In this example, I can access "file1.txt" as test = section["file001"], so test = "file1.txt". Now, when I want to access every file of FileList one after each other, I could try the following:

i = 1
for i in range(1, (number_of_files + 1)):
    access_key = str("file_00" + str(i))
    print(section[access_key])

Now, this is my current solution and I don’t like that at all. First of all, it looks kind of messy in python, but I will also face problems when more than 9 files are listed in the config.
I could do it like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i = 1
for i in range(1, (number_of_files + 1)):
    if (i <= 9):
        access_key = str("file_00" + str(i))
    elif (i > 9 and i < 100):
        access_key = str("file_0" + str(i))
    print(section[access_key])

But I don’t want to start with that because it becomes even worse. So my question is: What would be a proper and relatively clean way to do that? I definitely need the "looped access" because I need to perform some actions with every file.

>Solution :

Use zero padding to generate the file number (for e.g. see this SO question answer: https://stackoverflow.com/a/339013/3775361). That way you don’t have to write the logic of moving through digit rollover yourself—you can use built-in Python functionality to do it for you. If you’re using Python 3 I’d also recommend you try out f-strings (one of the suggested solutions at the link above). They’re awesome!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading