There are operations that can be done with strings.
In [1]:
firstName = "Johan"
In [2]:
lastName = "Gambolputty"
When concatenating strings, we must explicitly use the concatenation operator +. Computers don't understand context.
In [3]:
fullName = firstName + lastName
In [4]:
print fullName
In [5]:
fullName = firstName + " " + lastName
In [6]:
print fullName
You can also think of strings as a sequence of smaller strings or characters. We can access a piece of that sequence using []. Gotcha - Python (and many other langauges) start counting from 0.
In [7]:
fullName[0]
Out[7]:
In [8]:
fullName[4]
Out[8]:
One more gotcha - in Python, if you want a range (or "slice") of a sequence, you get everything before the second index:
In [9]:
fullName[0:4]
Out[9]:
In [10]:
fullName[0:5]
Out[10]:
You can see some of the logic for this when we consider implicit indices
In [11]:
fullName[:5]
Out[11]:
In [12]:
fullName[5:]
Out[12]:
There are other operations defined on string data. IPython lets you do tab-completion after a dot ('.') to see what an object (i.e., a defined variable) has to offer. Try it now!
In [13]:
str.
Let's look at the upper method. What does it do? Lets take a look at the documentation. IPython lets us do this with a question mark ('?') before or after an object (again, a defined variable).
In [14]:
str.upper?
So we can use it to upper-caseify a string.
In [15]:
fullName.upper()
Out[15]:
You have to use the parenthesis at the end because upper is a method of the string class.
For what its worth, you don't need to have a variable to use the upper() method, you could use it on the string itself.
In [16]:
"Johann Gambolputty".upper()
Out[16]:
What do you think should happen when you take upper of an int? What about a string representation of an int?
In [ ]: