There are various ways to write print statements. In Python 3, to print to console you use print functions.
In the following lecture we will cover:
1. "%" notation for Strings, Floats, and Integers
2. Use the .format() method
3. Other Print function uses
Here is the basic way to print.
In [16]:
print("We are printing")
You can format your printing using percent notation. Recall, we use the following notation for various types:
Strings: %s
Integers: %d
Float: %f
In [17]:
s = "this is a string"
In [18]:
print("Well, %s" % (s))
Below, we are demoing printing floats.
In [19]:
my_float = 13.9
In [20]:
print("I've got %.2f apples" % (my_float))
We can add spaces to the output if we wanted to.
In [13]:
print("%10.2f <--- look at all of this space" % (my_float))
You can format multiple types of objects with the percent notation. Let's try a string, float, and integer.
In [15]:
name = "Michael"
age = 19
schooling = 4
print("Name: %s Age: %d Schooling Years: %0.1f" % (name, age, schooling))
Traditionally, string formatting has included using the percent notation with %s, %f, and %d. We've seen the syntax before in the String iPython notebook. Here we can see it again.
my_str.format(var1, var2)
In [2]:
my_str = "No one said becoming a {x} entrepreneur was as easy as {y} ({z})".format(x="tech", y=3.14, z="pie")
In [3]:
print(my_str)
The Python 3 print function is notated in the documentation as the following:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Let's see what "sep" means.
In [4]:
# Normal print
print("hello")
In [6]:
# Utilizing the "sep" parameter by simply adding multiple object arguments
print("hello", "there")
As you can see, the "sep" parameter adds a space of seperation between object arguments.