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

Convert a dynamically sized list to a f string

I’m trying to take a list that can be size 1 or greater and convert it to a string with formatting "val1, val2, val3 and val4" where you can have different list lengths and the last value will be formatted with an and before it instead of a comma.

My current code:

inputlist = ["val1", "val2", "val3"]
outputstr = ""
            for i in range(len(inputlist)-1):
                if i == len(inputlist)-1:
                    outputstr = outputstr + inputlist[i]
                elif i == len(inputlist)-2:
                    outputstr = f"{outputstr + inputlist[i]} and "
                else:
                    outputstr = f"{outputstr + inputlist[i]}, "
            print(f"Formatted list is: {outputstr}")

Expected result:

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

Formatted list is: val1, val2 and val3

>Solution :

join handles most.

for inputlist in [["1"], ["one", "two"], ["val1", "val2", "val3"]]:
    if len(inputlist) <= 1:
        outputstr = "".join(inputlist)
    else:
        outputstr = " and ".join([", ".join(inputlist[:-1]), inputlist[-1]])
    print(f"Formatted list is: {outputstr}")

Produces

Formatted list is: 1
Formatted list is: one and two
Formatted list is: val1, val2 and val3
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