Strings and Types

Authors: Tom Dunham
Date: 2009-03-31


>>> "hello world"
'hello world'
>>> "AA" + "BB"
>>> "=" * 10

String Expressions

>>> greeting = "hello"
>>> greeting
>>> greeting + " world"
'hello world'
>>> EcoRI = "GAATTC"
>>> EcoRI


Types (2)

Types (3)

We now have another way to describe size = 5

"Bind the name size to an object with the value 5 and the type int"

If we has said size = 5.0, then size would be bound to an object with the value 5.0 and the type float.

And if we had size = "large", the value would be large, and the type str (for string).

We have also used the boolean (bool) type in the tests we've written for if statements and while loops.

Types (4)

To get the type of a value, you can use the type function

>>> type(10)
<type 'int'>
>>> type(1.0)
<type 'float'>

>>> size = 10
>>> type(size)
<type 'int'>

Type Conversions

Python can convert some types in the manner you would expect

>>> 1 + 1.0

But some types cannot be converted implicitly

>>> 1 + "1"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Explicit conversions

You can attempt to convert a value to another type

>>> float(1)
>>> int(1.1)
>>> str(1)
>>> int("hello world")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'hello world'

String operations

Not all operations have symbolic names like +

>>> EcoRI
>>> EcoRI.lower()

EcoRI is a name which is bound to an object with type string and value GAATTC. The string object supports an operation called lower which returns a new object of type string but with value gattc.

String Operations (2)

It's the string object that supports the operation

>>> "hello".upper()
>>> "TACTTTATATTTTA".replace("T", "U")
>>> EcoRI = "GAATTC"
>>> seq.count(EcoRI)
This is the point where I start giving examples with a bias toward biology. Sadly my Biology education ended at the age of 16, so it's likely that in contriving examples to demonstrate the programming language I've made huge mistakes with the Biology. If so please accept my apologies and correct me.

Some terms

We have seen a number of ways to invoke operations:

Using functions
>>> square(2)
Using operators
>>> 2 + 2
Using methods
>>> "TACTTTATATTTTA".replace("T", "U")

A method is a function that is "stuck" to an object. It always acts upon the object, but can take other parameters as well.

A small number of operations and their notations are well known from other fields (particularly mathematics). To make these operations easier to read, Python allows the programmer to write them in a familiar manner, when Python evaluates these expressions, it turns them into functions - 2 + 2 becomes (2).__add__(2).

Strings as sequences

A string is a sequence of characters, and you can process it one character at a time:

gaps = 0
for base in seq:
    if base == "-":
       gaps = gaps + 1
print "There are", gaps, "gaps in sequence"


  1. What are the types of these expressions (try to work them out first, then check using Python):

    1. 7
    2. "abc"
    3. 5.5
    4. True
    5. 2 == 3
    6. 5.0 / 2.0
    7. 5.0 / 2
    8. 5 / 2
  2. After executing the following:

    def square(x):
        return x * x

    What is type(square)?


  1. Count the number of bases in seq

  2. Write a function to calculate the GC ratio of a sequence, and try seq

    Where GC ratio is calculated by: (A + T) / (G + C) (that's was it says on Wikipedia:

  3. Write a function that reverse-transcribes RNA to DNA


Modules contain functions (and objects) that you can import and use in your program

>>> import string

A module is an object

>>> string
<module 'string' from 'C:\Python25\lib\string.pyc'>
>>> string.uppercase

Importing names

>>> from string import maketrans

maketrans is a function

>>> maketrans
<built-in function maketrans>


Python comes with built-in help

Try it

>>> help()

Note that the prompt changes to help>

>>> import string
>>> help(string.maketrans)

String Translations

To convert vowels into numbers:

>>> tt = maketrans("aeiou", "01234")
>>> "fantastic".translate(tt)

Strings and sequences

You can get characters from a string by index

>>> EcoRI
>>> EcoRI[1]
>>> EcoRI[0]
>>> EcoRI[-1]


A string can be sliced, to give copies of substrings.

>>> EcoRI
>>> EcoRI[1:3]
>>> EcoRI[1:]
>>> EcoRI[1:-1]


You can get the length of a string using len.

>>> len(EcoRI)
>>> EcoRI[1:3]
>>> len(EcoRI[1:3])

Strings Review