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
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")
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"
Concatenate and print multiple strings with plus
In case a variable is not of string type, it needs to be converted to string using
print "Hello" + " World" i = 2 print "Hello" + str(i)
Hello World Hello2
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