Intro to operations on strings


Loosely Based on Lecture Materials By: Milad Fatenejad, Katy Huff, Joshua R. Smith, Tommy Guy, Will Trimble, and Many More

There are operations that can be done with strings.


In [21]:
firstName = "Johan"

In [22]:
lastName = "Gambolputty"

When concatenating strings, we must explicitly use the concatenation operator +. Computers don't understand context.


In [23]:
fullName = firstName + lastName

In [24]:
print fullName


JohanGambolputty

In [25]:
fullName = firstName + " " + lastName

In [26]:
print fullName


Johan Gambolputty

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 [27]:
fullName[0]


Out[27]:
'J'

In [28]:
fullName[4]


Out[28]:
'n'

One more gotcha - in Python, if you want a range (or "slice") of a sequence, you get everything before the second index:


In [29]:
fullName[0:4]


Out[29]:
'Joha'

In [30]:
fullName[0:5]


Out[30]:
'Johan'

You can see some of the logic for this when we consider implicit indices


In [31]:
fullName[:5]


Out[31]:
'Johan'

In [32]:
fullName[5:]


Out[32]:
' Gambolputty'

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 [ ]:
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 [1]:
str.upper?

So we can use it to upper-caseify a string.


In [ ]:
fullName.upper()

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 [ ]:
"Johann Gambolputty".upper()

What do you think should happen when you take upper of an int? What about a string representation of an int?


In [ ]: