{ "metadata": { "name": "", "signature": "sha256:a37edb935ad28d94d46c6e95f7c688ffca27fce4be1071140fe3d8ab1a731d24" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# String Formatting\n", "\n", "- **Author:** [Chris Albon](http://www.chrisalbon.com/), [@ChrisAlbon](https://twitter.com/chrisalbon)\n", "- **Date:** -\n", "- **Repo:** [Python 3 code snippets for data science](https://github.com/chrisalbon/code_py)\n", "- **Note:**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Import the sys module" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import sys" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print a string with 1 digit and one string." ] }, { "cell_type": "code", "collapsed": false, "input": [ "'This is %d %s bird!' % (1, 'dead')" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 1, "text": [ "'This is 1dead bird!'" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print a dictionary based string" ] }, { "cell_type": "code", "collapsed": false, "input": [ "'%(number)d more %(food)s' % {'number' : 1, 'food' : 'burger'}" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "'1 more burger'" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print a string about my laptop." ] }, { "cell_type": "code", "collapsed": false, "input": [ "'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'laptop'})" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 6, "text": [ "'My laptop runs darwin'" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## String Formatting Codes\n", "- %s string\n", "- %r repr string\n", "- %c character (integer or string)\n", "- %d decimal\n", "- %i integer\n", "- %x hex integer\n", "- %X same as X but with uppercase\n", "- %e floating point lowercase\n", "- %E floating point uppercase\n", "- %f floating point decimal lowercase\n", "- %F floating point decimal uppercase\n", "- %g floating point e or f\n", "- %G floating point E or F\n", "- %% literal %" ] } ], "metadata": {} } ] }