Home > Back-end >  Convert a dynamically sized list to a f string
Convert a dynamically sized list to a f string

Time:11-27

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

CodePudding user response:

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

CodePudding user response:

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}")
  • Related