Subroutine7901
Subroutine7901

Reputation: 1

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:

Formatted list is: val1, val2 and val3

Upvotes: 0

Views: 59

Answers (3)

Sanjay Muthu
Sanjay Muthu

Reputation: 1

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(The official webiste),

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

Upvotes: 0

Subroutine7901
Subroutine7901

Reputation: 1

Decided to use string methods instead, and it worked perfectly.

outputstr = str(inputlist).replace("'", "").strip("[]")[::-1].replace(",", " and"[::-1], 1)[::-1]
            print(f"With the following codes enabled: {outputstr}")

Upvotes: 0

jwal
jwal

Reputation: 660

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

Upvotes: 1

Related Questions