Issue
I have data that looks like this:

Now I want to make a string that has a format like this:
Hello {first_name} {last_name}, this is the list of fruit that you want
- {fruit_0} with {colour_0} colour
- {fruit_1} with {colour_1} colour
- {fruit_2} with {colour_2} colour
So the expected output would be (example first row):
Hello Maria White, this is the list of fruit that you want
1. apple with pink colour
But when I code it turns out:
Hello Maria White, this is the list of fruit that you want
1. apple with pink colour
2. - with - colour
3. - with - colour
This the code that I used:
import pandas as pd
df = pd.read_excel("fruit.xlsx")
for x in x.dfitertuples():
first_name = x.first_name
last_name = x.last_name
fruit_0 = x.fruit_0
fruit_1 = x.fruit_1
fruit_2 = x.fruit_2
colour_0 = x.colour_0
colour_1 = x.colour_1
colour_2 = x.colour_2
message = f"""
Hello {first_name} {last_name}, this is the list of fruit that you want
1. {fruit_0} with {colour_0} colour
2. {fruit_1} with {colour_1} colour
3. {fruit_2} with {colour_2} colour
"""
print(message)
Thank you
Solution
Use an array to store the colours and fruits. This way you can iterate through all the colour/fruit pairs.
import pandas as pd
df = pd.read_excel("fruit.xlsx")
for x in x.dfitertuples():
first_name = x.first_name
last_name = x.last_name
fruits = [x.fruit_0,x.fruit_1,x.fruit_2]
colours = [x.colour_0,x.colour_1,x.colour_2]
print(f"Hello {first_name} {last_name}, this is the list of fruit that you want")
for i in range(fruits):
if fruits[i] and colours[i]:
print(f"{i+1}. {fruits[i]} with {colours[i]} colour")
Answered By - Rohan Dayaram Answer Checked By - Terry (sql.easybugfix Volunteer)
Post a Comment
Post a Comment