#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2004
    Posts
    330
    Rep Power
    15

    Don't need gap between char and digit


    Hello,

    I am printing some characters in a line and their positions using this statement:
    Code:
    print char,pos
    and a typical output is;
    Code:
    F 3
    S 4
    K 7
    A 12
    However the output that I prefer is this;
    Code:
    F3
    S4
    K7
    A12
    How can I get rid of the gap inbetween?

    Thanks for your help.
  2. #2
  3. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    14
    Hi sam,

    use a formatted string:
    Code:
    print "%s%d"%(char,pos)
    For more info have a look at:
    Python String Formatting

    Because %s can be used to convert an object to a string
    Code:
    print "%s%s"%(char,pos)
    is also valid.


    grim
    Last edited by Grim Archon; February 27th, 2006 at 02:45 AM.
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2004
    Posts
    330
    Rep Power
    15
    Thanks alot, that does the job!
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2003
    Location
    Lisbon, Portugal
    Posts
    154
    Rep Power
    13
    Alternatively, if you're used to other programming languages, you can:

    python Code:
    import sys
    sys.stdout.write(char)
    sys.stdout.write(str(pos))


    Unfortunately, this method doesn't automatically convert whatever into strings, so you can't print out an integer without explicitly converting before-hand.

    sys.stdout is a file-like object, which you can write to, but if you want a newline, you explicitely add a "\n" to it. Also, as far as I know, print makes a call to sys.stdout.write(whateverYouWannaPrint + "\n")



    P.S. Just noticed, the first sys on the highlighted code isn't red.
    "Get it hot! Hit it harder!!!"
    --- The tutor warcry

    ActivePython
    Mark Pilgrim's Dive into Python E-book, thank this guy for his contribution to the Python community!

IMN logo majestic logo threadwatch logo seochat tools logo