{ "metadata": { "name": "", "signature": "sha256:31b987c45a65482c448f440e7e93dc80fa8553dfea270678d1070166ab64e4c8" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Strings\n", "We use text all the time in science and computing to store information like:\n", "\n", "* Species names\n", "* Site names\n", "* Genetic sequences\n", "* Information about methods\n", "\n", "In Python we store this kind of data in strings.\n", "\n", "## Types\n", "Strings can have one of two major types in Python:\n", "\n", "* str: which handles all of the characters in the Latin alphabet (basically anything you'll find on a keyboard in North America)\n", "* unicode: which handles basically anything that would be a on keyboard anywhere\n", "\n", "We'll work with str here, but everything is basically the same using unicode." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Creating strings\n", "----------------\n", "Strings are created using either single or double quotes. It doesn't typically matter which kind of quotes you use, but they do need to match." ] }, { "cell_type": "code", "collapsed": false, "input": [ "genus = 'Dipodomys'\n", "species = \"spectabilis\"\n", "print(genus)\n", "print(species)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Dipodomys\n", "spectabilis\n" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we want to create a string that has multiple lines we can do this using triple quotes." ] }, { "cell_type": "code", "collapsed": false, "input": [ "ds_description = \"\"\"Dipodomys spectabilis is the\n", "scientific name for the\n", "Banner-tailed Kangaroo Rat.\"\"\"\n", "print ds_description" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Dipodomys spectabilis is the\n", "scientific name for the\n", "Banner-tailed Kangaroo Rat.\n" ] } ], "prompt_number": 2 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Determining the length of a string" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python uses a single function to determine the length of most things including strings, the `len()` function." ] }, { "cell_type": "code", "collapsed": false, "input": [ "latin_binomial = \"Dipodomys ordii\"\n", "len(latin_binomial)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 3, "text": [ "15" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Concatenating strings\n", "We can combine strings using the + operator." ] }, { "cell_type": "code", "collapsed": false, "input": [ "genus + species + 'weighs about 125 grams.'" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 4, "text": [ "'Dipodomysspectabilisweighs about 125 grams.'" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we want spaces between words we need to add them explicitly." ] }, { "cell_type": "code", "collapsed": false, "input": [ "genus + ' ' + species + ' weighs about 125 grams.'" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "'Dipodomys spectabilis weighs about 125 grams.'" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Formatted strings\n", "A better way to achieve this type of output in Python is using formatted strings. Everywhere we want to place a variable or a value in the string we place a % followed by a letter that tells it how we want the information formatted (like a string, an integer, a float, etc.) then after the string we add a % and then a comma separated list of the values/variables to insert in parentheses." ] }, { "cell_type": "code", "collapsed": false, "input": [ "output = \"%s %s weighs about %d grams.\" % (genus, species, 125)\n", "print output" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Dipodomys spectabilis weighs about 125 grams.\n" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Escape Characters\n", "Sometimes in programming we need to change the way a character works, or add a special character to a string. To do this we use escape characters. For example, what if we want to include an apostrophy in a string? If we just add it then things go wrong:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print('The individual's mass is 122 grams.')" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 1)", "output_type": "pyerr", "traceback": [ "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m print('The individual's mass is 122 grams.')\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n" ] } ], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This happens because when Python encounters the apostrophy it thinks we're telling it to end the string and it doesn't understand what all of the stuff coming after the string is.\n", "\n", "To tell Python that we actually want an apostrophy we use an escape character, the \\ in this case, so instead of typing ' we type \\'" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print('The individual\\'s mass is 122 grams.')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The individual's mass is 122 grams.\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other escape characters include:\n", "\n", "* \\\" - Double quotation mark\n", "* \\t - Tab\n", "* \\n - New line\n", "* \\\\\\\\ - Backslash\n", "\n", "Doubling up the escape character to get the character itself is the standard approach to handling that character.\n", "\n", "In fact, if we look at our multi-line string from above, we'll see that it is actually just a regular string, with some new lines inserted using \\n." ] }, { "cell_type": "code", "collapsed": false, "input": [ "ds_description" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 9, "text": [ "'Dipodomys spectabilis is the\\nscientific name for the\\nBanner-tailed Kangaroo Rat.'" ] } ], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because Python allows both single quotes and double quotes, there is also an easy way to avoid escaping characters in some cases. For example," ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(\"The individuals's mass is 122 grams.\")\n", "print('The original paper states that \"The mass of Dipodomys spectabilis is approximately 125 grams.\"')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The individuals's mass is 122 grams.\n", "The original paper states that \"The mass of Dipodomys spectabilis is approximately 125 grams.\"\n" ] } ], "prompt_number": 10 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "The String Module" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There is a string module that has a lot of useful functions for working with strings. Functions in this module can change capitalization (`upper`, `lower`, `capitalize`), remove excess whitespace (`strip`), find the location of substrings (`find`), split a string into pieces (`split`), and count the number of occurrences of particular characters (`count`)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "import string\n", "\n", "genus = 'Dipodomys'\n", "species = ' spectabilis'\n", "latin_binomial = 'Dipodomys ordii'\n", "dna_seq = 'atgcagatcctgtgtgtctagctaag'\n", "\n", "print(\"The lower case version of genus is: %s\" % string.lower(genus))\n", "print(\"The upper case version of species is: %s\" % string.upper(species))\n", "print(\"The value of species without the leading whitespace is: %s\" % string.strip(species))\n", "print(\"The location of the start of the first 'tcct' in dna_seq is: %s\" % string.find(dna_seq, 'tcct'))\n", "print(\"The number of a's in dna_seq is: %s\" % string.count(dna_seq, 'a'))\n", "genus, species = string.split(latin_binomial)\n", "print(\"The genus in latin_binomial is: %s\" % genus)\n", "print(\"The species in latin_binomial is: %s\" % species)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The lower case version of genus is: dipodomys\n", "The upper case version of species is: SPECTABILIS\n", "The value of species without the leading whitespace is: spectabilis\n", "The location of the start of the first 'tcct' in dna_seq is: 7\n", "The number of a's in dna_seq is: 6\n", "The genus in latin_binomial is: Dipodomys\n", "The species in latin_binomial is: ordii\n" ] } ], "prompt_number": 11 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "String Methods" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Many kinds of objects in Python carry their own functions with them. These kinds of functions are called `methods`.\n", "\n", "Instead of doing something to any object, methods do something to the object they are attached to.\n", "\n", "To call a method for a particular object we use the object name, followed by a period (called a dot), followed by the name of the method. For example, if we want to make all of the letters in a string capitals we can use the `.upper()` method." ] }, { "cell_type": "code", "collapsed": false, "input": [ "genus = \"Dipodomys\"\n", "upper_cased_genus = genus.upper()\n", "print upper_cased_genus" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "DIPODOMYS\n" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": {}, "source": [ "All of the functions that are available in the strings module are also available as methods." ] }, { "cell_type": "code", "collapsed": false, "input": [ "genus = 'Dipodomys'\n", "species = ' spectabilis'\n", "latin_binomial = 'Dipodomys ordii'\n", "dna_seq = 'atgcagatcctgtgtgtctagctaag'\n", "\n", "print(\"The lower case version of genus is: %s\" % genus.lower())\n", "print(\"The upper case version of species is: %s\" % species.upper())\n", "print(\"The value of species without the leading whitespace is: %s\" % species.strip())\n", "print(\"The location of the start of the first 'tcct' in dna_seq is: %s\" % dna_seq.find('tcct'))\n", "print(\"The number of a's in dna_seq is: %s\" % dna_seq.count('a'))\n", "genus, species = latin_binomial.split()\n", "print(\"The genus in latin_binomial is: %s\" % genus)\n", "print(\"The species in latin_binomial is: %s\" % species)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The lower case version of genus is: dipodomys\n", "The upper case version of species is: SPECTABILIS\n", "The value of species without the leading whitespace is: spectabilis\n", "The location of the start of the first 'tcct' in dna_seq is: 7\n", "The number of a's in dna_seq is: 6\n", "The genus in latin_binomial is: Dipodomys\n", "The species in latin_binomial is: ordii\n" ] } ], "prompt_number": 13 } ], "metadata": {} } ] }