Hello all I have been a hobbiest programmer for quite some time now and recently got back into it. I'm starting with a pretty simple program that will track inventory for my moms buisness. I've worked through most the common problems but can't seem to figure out why im getting extra spaces when displaying my list. I have been tempted to believe its because of the \n being carried along, but cannot prove it to myself by common debugging. Here is the code.

#display contents of the inventory file
def display():
    tmpc = 0
    counter = 0
    contents = []
    temp = []
    #open inventory and add contents to contents list
    newfile = open("inventory.txt", "rt")
    for item in newfile:
        contents.append(item)
    newfile.close()
    #open counter file and update counter variable
    cfile = open("counter.txt", "rt")
    counter = cfile.read()
    cfile.close()
    counter = int(counter)
    if counter == 0:
        return print("list empty")
    else:
    #check counter and length of contents to confirm
    #there is data in the inventory file
    #display a numbered list by combinding the counter file
    #and inventory file information
        if not counter > len(contents) and not counter < 0:
            while tmpc < counter:
                print(repr(tmpc) + "." + contents[tmpc])
                tmpc = tmpc + 1
        else:
            return print("Error inventory and counter files do not match.")

Then I simply call the function from a menu within the actual program. Thanks an can't wait to get some replies. :)

Recommended Answers

All 4 Replies

#open inventory and add contents to contents list
    newfile = open("inventory.txt", "rt")
    for item in newfile:
        ## Use strip here to remove the newlines that you're reading in
        contents.append(item.strip())
    newfile.close()

You're right... it's important to remember that when reading files, each line has a newline on the end of it. It's usually a good idea to always use strip() to strip the white space off of the end (as well as the beginning of the line - so if you've got tabs or spaces prepending your text use rstrip to only get the right side of the line clear of white space).

Works like a charm, thanks for clearly stating what strip is used for as well. Hopefully I can get to a point where I can understand the definitions of functions in the python library so I can look that kind of thing up on my own withough frying to many brain cells.

Here's a trick to keep in your back pocket: docs.python.org (note the site is down right now).

That's the absolute best resource for discovering things and answering your questions about Python (next to DaniWeb, naturally!)

And whenever you're confused about the usage of a particular function in Python you can always fire up your interpreter and use help(function) . For example:

Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> my_string = 'foobar'
>>> help(my_string.strip)
Help on built-in function strip:

strip(...)
    S.strip([chars]) -> str

    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
>>>

Another thing to keep in mind is that you can query the members and methods of any object (and since everything in Python is an object that means you can query ANYTHING!) using dir. This in combination with help can really get you far when in discovery/test mode.

>>> dir(my_string)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt_
_', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__'
, '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__
rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
 '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'co
unt', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum',
'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'ispr
intable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', '
maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'r
split', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'tit
le', 'translate', 'upper', 'zfill']
>>>

Note that the things that are surrounded by double underscores (__) are "private" in the sense that you're not supposed to use them. They're helper functions that you can even take advantage of and overload when creating your own objects. A quick way to get around seeing them when using dir is this handy little list comprehension:

>>> [ item for item in dir(my_string) if item[0] != '_' ]
['capitalize', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'f
ormat', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', '
islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', '
ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex
', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith
', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

Thanks!! I can see myself using this quite a bit as typing something"." will give me a nice list of options. Getting info on what they are for from right within python will be very usefull. Time to bust out an idle session. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.