Home > Blockchain >  Extract elements from dynamic list as increases or decreases in python3
Extract elements from dynamic list as increases or decreases in python3

Time:02-10

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 (new line) 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 

CodePudding user response:

You can use a list comprehension and enumerate() to create the dynamic list and join() the elements by new line character:

mylist = ['Tuesday 08  2022','Wednesday 09  2022','Thursday 10  2022','Friday 11  2022']

data = '\n'.join([f"{i}. {e}" for i,e in enumerate(mylist,start=1)])

print(f"the forecast for the week is (choose number):\n{data}")

Output

the forecast for the week is (choose number):
1. Tuesday 08  2022
2. Wednesday 09  2022
3. Thursday 10  2022
4. Friday 11  2022

CodePudding user response:

You could write a loop for your list and put the print statement in that. Something like:

my_list = ["a","b","c"]
print(f"the forecast for the week is (choose number):")
for idx, word in enumerate(my_list):
    print(f"{str(idx)}. {word}")
print(f"{str(len(my_list))}. Show all week")

This should be dynamic for your list

  • Related