greyxray
greyxray

Reputation: 400

Skip new line while printing with ternary operator in python

To print a statement and to prevent going into the new line one could simply add a comma in the end:

print "text", 

But how can I do the same using a ternary operator? This one causes invalid syntax:

print ("A", if True else "B", )

Upvotes: 1

Views: 307

Answers (5)

turkus
turkus

Reputation: 4903

Instead of using just ugly hacks, we can define function called below as special_print which every print locates in the same line:

import sys


def special_print(value):
    sys.stdout.write(value)


special_print('ab')
special_print('cd')

Result:

abcd

You can even mix normal print with special_print:

print('whatever')
special_print('ab')
special_print('cd')

Result:

whatever
abcd

Of course you cannot use any expression as argument of special_print, but with displaying variable it just works.

Hope that helps!

Upvotes: 1

[...] to prevent going into the new line one could simply add a comma in the end

The solution is in your question already. One could simply add a comma in the end:

print "A" if True else "B",

However Python 3 has been out for closer to a decade now so I will shamelessly plug the new print function that has much saner syntax:

from __future__ import print_function

print('A' if True else 'B', end=' ')

Future imports/Python 3 solved your problem efficiently, and the strange statement syntax is just a bad memory from past. As a plus, you're now forward-compatible!

Upvotes: 5

Ma0
Ma0

Reputation: 15204

You can use the or operator as well, like this:

a = None
b = 12
print a or b,
print "is a number"
# prints: 12 is a number

Just note that the expression above is evaluated lazily, meaning that if bool(a) is False, print will return b even if that evaluates to False too since it wouldn't bother checking (therefore a or b is not equal to b or a generally speaking). In the above example for instance, if b = "" it would just print "is a number" (example).

Upvotes: 0

Ayan Shafqat
Ayan Shafqat

Reputation: 98

I guess you can look at it this as one statement:

"A" if True else "B"

Then your print statement becomes:

print "A" if True else "B",

That should print "A" without the newline character (or "B" if the condition is False).

Upvotes: 1

User_Targaryen
User_Targaryen

Reputation: 4225

print "A" if True else "B",
print "Hi"

Output: A Hi

Upvotes: 1

Related Questions