[Tutor] Newbie append puzzle

Michael Janssen Janssen at rz.uni-frankfurt.de
Wed Nov 5 08:07:42 EST 2003


On Sun, 2 Nov 2003, Tim Ronning wrote:

> I have re-done a couple of things incl. the append function. Not shure if
> this is what you had in mind though. How do you test for "\n" in a string ?
> Anyway the following code works, but I greatly appriciate input on smarter
> ways to do things. Thats what learning is all about, -learning to do smart
> things!

>     def append(mp3):
>         if choice == "3":
>             app = open("playlist","a")
>             app.write(mp3)
>             app.close()
>         else:
>             app = open("playlist.new","a")
>             app.write(mp3 + "\n")
>             app.close

yes, you're right, this solution is somewhat unsmart: since "append"
uses a big deal of knowledge of how the rest of the script works, you
will often need to reflects changes in the core part of your script
within "append". Many errors and hard maintance might be a result.

It's better to make the "append" function tough enough that it doesn't
need to know which choise was made and if the choice preserve the
newline. This brings me back to your question: How to test for "\n".

You can test for any character on any position in a string via slices
(check the library reference for this:
http://www.python.org/doc/current/lib/typesseq.html or the tutorial:
http://www.python.org/doc/current/tut/node5.html (somewhere down the
side):

if "test"[1] == "e":
    print "yes"

if mp3[-1] != "\n":
    mp3 = mp3 + "\n"


or even better use the stringsmethod endswith:

if not mp3.endswith("\n"):
    mp3 = mp3 + "\n"

i would take for "append" (with an optional parameter playlist):

def append(mp3, playlist="playlist"):
    if not mp3.endswith("\n"):
        mp3 = mp3 + "\n"
    app = open(playlist,"a")
    app.write(mp3)
    app.close()

this way you get, with a little luck, functions
once-defined-working-ever. Helps much to concentrate on new-to-write
functionality.

Michael



More information about the Tutor mailing list