Convert a dynamically sized list to a f string

Question:

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:

Formatted list is: val1, val2 and val3
Asked By: Subroutine7901

||

Answers:

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
Answered By: jwal

The range function in python does not include the last element,
For example range(5) gives [0, 1, 2, 3, 4] only it does not add 5 in the list,

So your code should be changed to something like this:

inputlist = ["val1", "val2", "val3"]
outputstr = ""

for i in range(len(inputlist)):
    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}")
Answered By: Sanjay Muthu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.