Python - Print

> Procedural Languages > Python

1 - Syntax

print ("%s" % (string_variable))

where:

  • the first Parenthese are only needed for python 3 as print is a function.
  • The % string formatter replace
  • The %s (%s is a place holder where the “s” is for “string”)
  • with string_variable

2 - Example

2.1 - Python 2

print "My last name is %s and my first-name is %s" % ("Gerard", "Nico")

2.2 - Python 3

In python 3, print becomes a function

print ("My last name is %s and my first-name is %s" % ("Gerard", "Nico")) 
Advertising

3 - No new line

By appending a , at the end of the statement, you prevent the print function to add a newline

print "Lines without",
print "New Line",
Lines without New Line

4 - Explicit Number transformation and String Concatenation

dictionary = {'key1': 1, 'key2': 2, 'key3': 3}
 
for key in dictionary:
    print key, ":" ,  dictionary[key]
key3 : 3
key2 : 2
key1 : 1