Hacking Secret Ciphers with Python

(Ann) #1
Chapter 4 – Strings and Writing Programs 39

String Replication with the * Operator


You can also use the * operator on a string and an integer to do string replication. This will
replicate (that is, repeat) a string by however many times the integer value is. Type the following
into the interactive shell:





'Hello' 3
'HelloHelloHello'
spam = 'Abcdef'
spam = spam
3
spam
'AbcdefAbcdefAbcdef'
spam = spam * 2
spam
'AbcdefAbcdefAbcdefAbcdefAbcdefAbcdef'





The * operator can work with two integer values (it will multiply them). It can also work with a
string value and an integer value (it will replicate the string). But it cannot work with two string
values, which would cause an error:





'Hello' * 'world!'
Traceback (most recent call last):
File "", line 1, in
TypeError: can't multiply sequence by non-int of type 'str'





What string concatenation and string replication show is that operators in Python can do different
things based on the data types of the values they operate on. The + operator can do addition or
string concatenation. The * operator can do multiplication or string replication.


Printing Values with the print() Function


There is another type of Python instruction called a print() function call. Type the following
into the interactive shell:





print('Hello!')
Hello!
print(42)
42




Free download pdf