Python: let's play with the Print function

Simplest print statements

# single line
print("test's")
print('test\'s')
# We need to escape the quote character used (simple or double quote)
print("test's \n second line")

You can also avoid the \n with the following

print("""This automatically
takes the new lines
""")
print("test" "again") # this concatenates the two pieces of string litteral
# testagain
print("test"
      "text on several lines but dispayed as one")
# testtext on several lines but dispayed as one
print("test" + "again") # but this is better
# testagain
print("test", "again") # this is concatenation using the print function separator
# test again

 

Print options and parameters

You can specify a separator between the concatenated values (by default it is the space character " ")

print("test", "again", sep = "-")
# this will concatenate using the 'sep' variable as separator
# test-again
print("test", "again", sep = "\n")
# multiple lines
# test
# again

You can also specify a character to put at the end of the concatenated string:

a,b = 0,1
print("values :", a, b, end="\n")
# it is possible to print litteral strings and variable
# the last character of the printed text is defined by the 'end' variable
# values : 0 1
#

The normal behaviour of python can be modified when it comes to the escape character:

print('C:\some\name')
# C:\some
# ame
# here we have a problem, this file path isn’t correctly printed
# to avoid this \n behavious use the r command before quotes
print(r'C:\some\name')
# C:\some\name

Printing and variables

print("n"*5) # repeats 'n' 5 times
# nnnnn
test = "blablablabla"
print(test[2:5])
# abl
print(test[:])
# blablablabla
# note that it is not possible to modify the string via the array synthax
print(len(test[:-1]))
# 11
listData = [1,2,3,4,5]
list2 = [7,8,9]
list3 = ['d',5,4.5]
print(listData + list2 + list3)
# [1, 2, 3, 4, 5, 7, 8, 9, 'd', 5, 4.5]
# list concatenation works great
Matthieu Liatard
Remember this!
Remember this
Play!
Take a quizz on this subject
Close

Hello :)
At Question-Player, we want to share more knowledge and help you never forget anything ever. And for free.

To show us your support, you can create an account:

Login / Create an account
Rate this article :
1
2
3
4
5

Up next

Related posts