print "foo", without a space

Michael Hudson mwh21 at cam.ac.uk
Thu Nov 11 16:02:24 CET 1999


Mikael Johansson <mikael.johansson at helsinki.xx> writes:

> Hello All!
> 
> Is there another way of getting print to not make a newline than
> using:
>     print "foo",  ?

I think there's some way invloling sys.stdout.softspace, but I'm no
sure what. However...

> This because the comma always produces a space which necessary
> isn't that nice, for example:
> 
> for i in range (1,30):
>     print i,
>     if i%10==1 and i<>11: print "st",
>     elif i%10==2 and i<>12: print "nd",
>     elif i%10==3 and i<>13: print "rd",
>     else: print "th",
>     print "fish"
>  
> Now you would like the "endings" to come right after the number.
> There is naturally always some way to get around this, in this
> case for example:
> 
> end=["st","nd","rd","th"]
> for i in range(1,30):
>     print `i`+end[max(min(abs(i)%10,4)-1-
>     4*(not(int('0'+`abs(i)`[-2:-1])-1)),-1)],'fish'
> 
> OK, this got a bit out of hand, 

!

> the above looks terrible, does 
> anyone see how it could be simplified? At least it's more general
> than the above as it can handle the whole range of integers,
> including negative ones :-) However it shows that it would be
> less obfuscating to have a print statement that could continue
> printing on the same line without a space.

Do you know about the string % operator? Try:

def ordinate(n):
    if n%10 == 1 and n <> 11:
        return "st"
    if n%10 == 2 and n <> 12:
        return "nd"
    else:
        return "th"

print "This is the %d%s fish"%(i,ordinate(i))

It's generally the way to go for formatting output.

> If there isn't an easy way for this, I suggest the following:
>     print "foo".
> So that a dot at the end of the line would mean "no space either".

With all due respect: no chance.
 
> Appreciating any comments.

Hoping this helps,
Michael




More information about the Python-list mailing list