Hacking Secret Ciphers with Python

(Ann) #1

38 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


String Concatenation with the + Operator


You can add together two string values into one new string value by using the + operator. Doing
this is called string concatenation. Try entering 'Hello' + 'World! ' into the shell:





'Hello' + 'World!'
'HelloWorld!'





To put a space between “Hello” and “World!”, put a space at the end of the 'Hello' string and
before the single quote, like this:





'Hello ' + 'World!'
'Hello World!'





Remember, Python will concatenate exactly the strings you tell it to concatenate. If you want a
space in the resulting string, there must be a space in one of the two original strings.


The + operator can concatenate two string values into a new string value ('Hello ' +
'World!' to 'Hello World!'), just like it could add two integer values into a new integer
value (2 + 2 to 4 ). Python knows what the + operator should do because of the data types of the
values. Every value is of a data type. The data type of the value 'Hello' is a string. The data
type of the value 5 is an integer. The data type of the data that tells us (and the computer) what
kind of data the value is.


The + operator can be used in an expression with two strings or two integers. If you try to use the



  • operator with a string value and an integer value, you will get an error. Type this code into the
    interactive shell:





'Hello' + 42
Traceback (most recent call last):
File "", line 1, in
TypeError: Can't convert 'int' object to str implicitly
'Hello' + '42'
'Hello42'




Free download pdf