Python Forum
Help Formatting Print Statement (input from 3 lists) X 2
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help Formatting Print Statement (input from 3 lists) X 2
#1
I am working on my class project and am having some difficulty getting my print statement to format "neatly". Teacher wants it to look like this when it prints-- ex.'TrapperKeeper________$3.99________13' So, 'product', 'price' and 'quantity'

I am also having similar issues formatting the text I am saving in the .txt file at the end (want to have each field separated by a ' : ')

Here is the code for the first issue:

def calculateTotal(products, prices, item_nums, quantity):
        subtotal = 0
        partial_summary = ''
        order_total = 0
        print()

        print('Items ordered list')
        print('------------------')
        width = 6
        a = 0
        b = 0
        t = len(item_list)

        while b < t:
            qty = float(quantity_list[b])
            a = int(item_list[b])
            price = float(prices[a])
            subtotal = (qty * price)
            order_total = order_total + subtotal
            print(products[b], '\t\t\t', '$', prices[a], '\t\t', quantity)
            b = b + 1
And this is the save to file script, which is ugly, but functional. I just need it to format more neatly as well. I have always had trouble with formatting things to actually look readable and nice, which may be my project over the holidays.

def data_save():
        fileWrite = open('OrdersArchive.txt', 'a')
        fileWrite.write(str(now))
        fileWrite.write(str(cust_name))
        fileWrite.write(str(street))
        fileWrite.write(str(city))
        fileWrite.write(str(state))
        fileWrite.write(str(zipcode))
        fileWrite.write(str(order_summary))
        fileWrite.write(str(order_total))
        print()
        return ()
        data_save()
Reply
#2
Use use the format method of the str obj.
Example:
fmstr = '{scheme}://{host}/{path}'
scheme = 'http'
host = 'smegma.com'
path = '/spam'
print(fmstr.format(scheme=scheme, host=host, path=path))
will result in:
http://smegma.com/spam
Reply
#3
Errrm. I am sorry, I may have misstated my goal here. I am only trying to format the output of my fileWrite commands that I'm appending to the .txt file so that they'll be separated by colons. As in:
07:46 :: 11/30/2017 :: Rabbi Muffin Crumbles :: 43 Dietsoda Ln. :: Harpy :: IL :: 43454 :: "order summary" :: "order total"
Reply
#4
Could you post the rest of the code?
Reply
#5
Sure thing. It's a big one, just so you know...

def data_save():
    fileWrite = open('OrdersArchive.txt', 'a')
    fileWrite.write(str(now))
    fileWrite.write(str(cust_name))
    fileWrite.write(str(street))
    fileWrite.write(str(city))
    fileWrite.write(str(state))
    fileWrite.write(str(zipcode))
    fileWrite.write(str(order_summary))
    fileWrite.write(str(order_total))
    fileWrite.close()
    print()
    return ()
#above, i am noticing in my txt file output that order_summary and order_total are not printing. here i am just trying to find a way to format the fileout to be somewhat readable and neat.

# and thus begins my function to calculate final order total, shipping and state taxes
def calculateTotal(products, prices, item_nums, quantity):
    subtotal = 0
    partial_summary = ''
    order_total = 0
    print()

    print('Items ordered list')
    print('------------------')
    width = 6
    a = 0
    b = 0
    t = len(item_list)
#here is where i need help formatting the list items to look like " 'product'_________'price'__________'quantity' "
    while b < t:
        qty = float(quantity_list[b])
        a = int(item_list[b])
        price = float(prices[a])
        subtotal = (qty * price)
        order_total = order_total + subtotal
        print(products[b], '\t\t\t', '$', prices[a], '\t\t', quantity)
        b = b + 1

    if order_total < 40.00:
        order_total = round(order_total, 2)
        print("Final order subtotal is", order_total)
        order_total = order_total + 4.99
        print("$4.99 added to all orders under $40")
        print()
        order_total = round(order_total, 2)
    if state == 'CA':
        order_total = order_total * 1.08
        print('CA sales tax added')
    if state == 'NY':
        order_total = order_total * 1.07
        print('NY sales tax added')
    order_total = round(order_total, 2)
    print()
    print("Total with Shipping: $", order_total)
    print()

    return (subtotal, order_total)


import datetime
now = datetime.datetime.now()

products = ['Notebook', 'Atari 2600', 'TrapperKeeper', 'Mod Jeans', 'Insects', 'Harbormaster', 'Lobotomy', 'PunkRock',
            'HorseFeathers', 'Super Pants', 'Super Fuzz', 'Salami']
prices = ['1.99', '2.99', '3.99', '4.99', '5.99', '6.99', '7.99', '8.99', '9.99', '10.99', '11.99', '12.99']
item_nums = [1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12]
item_list = []
quantity_list = []
item_number = 0
quantity = 0

response = ''
cust_name = ''
street = ''
city = ''
state = ''
zipcode = 0
order_total = 0
order_summary = []
done = 0
order = 0
t = 0
i = len(products)
f1 = 0
f2 = 0

print("Jay's House of Rip-Offs\n\n")
titles = ('Item Number', 'Item Name', 'Price')
data = [titles] + list(zip(item_nums, products, prices))

for i, d in enumerate(data):
    line = '|'.join(str(x).ljust(16) for x in d)
    print(line)
    if i == 0:
        print('-' * len(line))

while True:
    order = str.upper(input("\nOrder products [Y / N]?: "))
    if order.strip() == 'N':
        break  # no buy break
    item_nums = input("Enter an item number: ")
    item_list.append(item_nums)
    quantity = input("How many? ")
    quantity_list.append(float(quantity))

if len(item_list) == 0:
    print("Thank you for browsing.")


else:
    print()
    cust_name = input("Enter name: ")
    street = input("Enter street address: ")
    city = input("Enter city or town name: ")
    state = str.upper(input("Enter two letter state or province: "))
    zipcode = input("Enter zipcode: ")
    f1, f2 = calculateTotal(products, prices, item_list, quantity_list)


data_save()
print('Remain Calm and Shop as Usual...')
Reply
#6
product, price, quantity = 'Hydro', 120.0, 65535
message = '{product}    ${price}    {quantity}'
print(message.format(product=product, price=price, quantity=quantity))
Hydro    $120.0    65535
Am I on the right track?
Reply
#7
You have a list and you want it written to a file with values separated with double colons?
Use str.join(): '::'.join(iterable)
About the 'product'____'price'____'quantity' formatting... See this.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#8
@wavic, I see what you're getting at, however, i have no idea how to implement that into my code. For example, is this going to be its own line of code, or will it be wrapped into one of the fileWrite lines? I put them all together in one line and it didn't like it. I got:
File "/Users/jaywinfrey/PycharmProjects/Project IV.py", line 2, in data_save
str.join('::'.join(now), '::'.join(cust_name), '::'.join(street), '::'.join(city), '::'.join(state),
TypeError: can only join an iterable
Reply
#9
Open a Python interpreter, create a small list of strings and run the code from my example. Use the created list in place of 'iterable', as an argument to join(). See what is the output. Get this and write it into a file. Do you know how to open a file for writing? How to write something in it?
You write in the file a string, right? Well '::'.join(iterable) will produce a string.

str is a data type just like int, float and so on. you do not use join() method like that: str.join(iterable).
'::' is a string like 'Alan', 'apple', 'rain' or 'How many Microsoft programmers does it take to change a lightbulb?' All of these are str type so they have method called join. For example: 'apple'.join(iterable). The 'iterable' must be a sequence of values. A list, tuple, or set. What you are doing is giving a single value to '::'.join(city). 'city' holds a single value, write.

Try this code
my_iterable = ['one', 'two', three', 'go']
my_string = ",".join(my_iterable)
print(my_string)
Or you may try with 'apple'.join(my_iterable)  Wink
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#10
@wavic I'm just that much of a newbie. I apologize, but I just don't get how to phrase my command to get it to work. Formatting was the big problem for me in Python this year...other than having a degree in literature.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Post IF Statement Input OrphanedSoul 2 2,275 Jun-04-2021, 05:03 PM
Last Post: deanhystad
  Problem with print formatting using definitions Tberr86 2 1,949 Mar-20-2021, 06:23 PM
Last Post: DPaul
Bug How to print only vowels from an input? PP9044 8 7,427 Feb-26-2021, 04:02 PM
Last Post: Serafim
  Print user input into triangle djtjhokie 1 2,343 Nov-07-2020, 07:01 PM
Last Post: buran
  How to print the docstring(documentation string) of the input function ? Kishore_Bill 1 3,500 Feb-27-2020, 09:22 AM
Last Post: buran
  Print the longest str from user input edwdas 5 4,052 Nov-04-2019, 02:02 PM
Last Post: perfringo
  How to print a statement if a user's calculated number is between two floats Bruizeh 2 2,352 Feb-10-2019, 12:21 PM
Last Post: DeaD_EyE
  if/else statement only outputs else statement regardless of input KameronG 2 2,560 Feb-08-2019, 08:04 AM
Last Post: KameronG
  How to force print statement to print on one line wlsa 4 3,503 Oct-28-2018, 09:39 PM
Last Post: wavic
  Print The Length Of The Longest Run in a User Input List Ashman111 3 3,141 Oct-26-2018, 06:56 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020