python print examples

Here are some examples you can print strings or variables in python on stdout.

Print a string with newline in the end

By default python will append a newline in the end.

print "Hello\n"
print "Hello2"
s = "Hello3"
print s
Hello

Hello2
Hello3
Env: Python 2.7.6

Print a string without newline

One can use sys.stdout.write to print without newline

import sys
sys.stdout.write("Hello-")
sys.stdout.write("World\n")
Env: Python 2.7.6

Print multiple strings with comma

Multiple strings or variables can be printed using comma and it will add space between the strings and newline after last string.
We can use sys.stdout.write to print without newline

v1 = "Hello"
print v1, "Hello2"
Hello Hello2
Env: Python 2.7.6

Concatenate and print multiple strings with plus

In case a variable is not of string type, it needs to be converted to string using str()

print "Hello" + " World"
i = 2
print "Hello" + str(i)
Hello World
Hello2
Env: Python 2.7.6

Print formatted string

Using %s will print arguments to string if needed using str(). You can also use %d to print integers. A detailed list can be seen at python site – string formatting operations.

s = "Hello"
i = 2
print "%s %s %d" % (s, i, i)
Hello 2 2
Env: Python 2.7.6

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments