'Extract elements from dynamic list as increases or decreases in python
Hello i have a dynamic list which increases or decreases accordingly from the extracted data from a site with BeautifulSoup
mylist = [a,b,c,d,.......]
how can i make the following fstring to be dynamic as the list increases or decreases?
fstr = print(f"the forecast for the week is (choose number): {nl}1. {mylist[0]}{nl}2. {mylist[1]}{nl}3. {mylist[2]}{nl}4. {mylist[3]}{nl}5. Show all week")
As you can see i want the elements of mylist to be seperated by \nl in the fstring and not join it to a string. Is this possible?
the Output is
the forecast for the week is (choose number):
1. Tuesday 08 2022
2. Wednesday 09 2022
3. Thursday 10 2022
4. Friday 11 2022
Solution 1:[1]
you could use the join method:
mylist = [1,2,3,4,5]
fstr = f'show this: {', '.join(mylist)}'
or you could do this:
fstr = f'show this: {str(mylist).removeprefix("[").removesuffix("]")}'
output:
show this: 1, 2, 3, 4, 5
to dynamically change the list, you would have a updater function, witch would update the values:
def update(values):
globals()["fstr"] = f'show this: {', '.join(list1+values)}'
but is not or you could pass the entire list instead:
def update(mylist):
globals()["fstr"] = f'show this: {', '.join(mylist)}'
to update them constantly, you would need a loop, like:
while updating:
... # updating the values
Solution 2:[2]
myCommaSeparatedValues = ', '.join(myList)
This should work, then insert this list into your fstr variable:
fstr = f"Show the following {myCommaSeparatedValues}"
NOTE: never call a variable list since you are overwriting the built-in class list. Call it myList instead.
In Python to print a newline you have to use the standard char '\n'.
I assume you have a nested list with this structure:
myList = [
['1', 'Monday', '08', 2022],
['2', 'Tuesday', '09', 2022]
]
You can print as you expected this way:
fstr = "The forecast for the week is (choose number):"
for i in myList:
fstr += f"\n{' '.join(i)}"
print(fstr)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
