{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Strings\n", "\n", "A string in python is an immutable sequence of characters.\n", "We've already seen that we can make strings by enclosing\n", "it in either single quotes `''` or double quotes `\"\"`.\n", "It does not\n", "matter which we use, though if we plan to contain one\n", "of a single or double quote inside the string, but not both,\n", "inside the string, then it is easier to choose the one\n", "we do not plan to use inside the string." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "astr = 'ah'\n", "bstr = \"won't\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### String Operators\n", "\n", "A couple of the standard operators have been defined to have meaning with strings:\n", "\n", "* `str1 + str2` -> returns a new string with `str1` and `str2` concatenated\n", "* `str1*n` -> returns a new string with `str1` repeated `n` times\n", "\n", "Note that `/` and `-` are not defined for strings." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "astr = 'ah'\n", "bstr = 'frog'\n", "print(astr+bstr)\n", "print(astr*5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These can also be combined:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('a'*3 + 'h'*3 + bstr)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Special Characters\n", "\n", "While most characters can simply be typed into a\n", "string, some characters don't have a clear way\n", "to type them into strings. These are known as special\n", "characters. The two most common special characters\n", "are:\n", "\n", "* `\\n` = newline\n", "* `\\t` = tab\n", "\n", "To use these, we simply type them as part of the\n", "string. For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "multiline = 'a string with\\na newline'\n", "print(multiline)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Escape Characters\n", "\n", "While many times simply selectively choosing whether\n", "to enclose a string in single or double quotes is\n", "sufficient, sometimes, it's not enough. For instance,\n", "maybe you need to have both an apostrophe and quotation\n", "marks inside your string. In these cases, we can escape\n", "the character with `\\`. This indicates that the character\n", "immediately following should not be treated as a character\n", "python recognizes for some purpose, but instead should show\n", "up as just that regular character in the string.\n", "\n", "* `\\'` = single quote\n", "* `\\\"` = double quote\n", "* `\\\\` = backslash (since `\\` is used to escape, to use it\n", " as a literal character, it must be used to escape itself)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "strquote = \"And Harry Potter said \\\"hello\\\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Strings as Lists\n", "Strings can be treated like lists in python. This means\n", "that we can perform the same operations we did with lists.\n", "\n", "#### Indexing and Slicing\n", "* indexing - with `strname[i]`\n", "* slicing - `strname[start:stop:stride]`.\n", "As with lists, indices start at 0 and for slicing,\n", "`stride` is optional and `start` or `step` can be left empty.\n", "\n", "#### Iteration\n", "The same two for loop styles we used for lists can also\n", "be used for iterating through a string:\n", "* iterating through index range and then indexing into string\n", "* iterating directly through the characters in the string\n", "\n", "#### Containing Items\n", "As with lists, we can check if a substring is in a string\n", "with `in`:\n", "\n", "#### Examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "alpha = 'abcdefghijklmnopqrstuvwxyz'\n", "print(alpha[0])\n", "print(alpha[:5])\n", "repeated = ''\n", "for ch in alpha:\n", " repeated += ch*2\n", "print(repeated)\n", "print('aa' in alpha)\n", "print('aa' in repeated)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### String Comparison\n", "We've seen comparison operators for numeric types already (aka\n", "`==`, `<`, `<=`, `>`, `>=`), but they can\n", "be used with strings as well. Take a look at the following code\n", "and try to predict what it will print:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "msg1 = \"Hello\"\n", "msg2 = \"Apple\"\n", "msg3 = \"Hello\"\n", "msg4 = \"apple\"\n", "\n", "print(msg1 == msg2)\n", "print(msg1 == msg3)\n", "\n", "\n", "print(msg1 < msg2)\n", "print(msg1 < msg4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You may have thought the output for the last 2 lines would be the same. To some extent, the comparisons will do alphabetical, but in reality it is comparing the numbers used to store each letter underneath. Because of how\n", "individual letters are stored as unique numbers by the computer, lower and uppercase letters end up at very different spots from one another, causing this to give different behavior depending on the case of the operands. All uppercase letters come before all lowercase letters as far as the computer is concerned." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions on Strings and String Methods\n", "\n", "### Functions\n", "We've seen previously how one of the built-in\n", "functions, `len`, can be applied to strings to\n", "determine the number of characters in the string.\n", "The `min` and `max` functions can also be applied\n", "to strings, returning the letter with a letters\n", "value increasing from A-Z then a-z (so all uppercase\n", "are smaller than all lowercase, just as with string\n", "comparison)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "msg = 'Python'\n", "print(len(msg))\n", "print('min is', min(msg), 'max is', max(msg))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### String Methods\n", "As with lists, strings have many methods associated\n", "with the specific object and invoked (called) with\n", "`strname.methodname(args)`. The full list\n", "of methods for strings is available in the\n", "[documentation](https://docs.python.org/3/library/stdtypes.html#string-methods), but some of the most\n", "commonly used methods are listed below.\n", "\n", "Because strings are immutable, none of these\n", "methods actually modify the string. In cases where\n", "the method returns a string, it is a new string and\n", "the original string is unchanged." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Conversion Methods\n", "* `upper()` -> returns copy of the string in all uppercase\n", "* `lower()` -> returns copy of the string in all lowercase\n", "* `capitalize()` -> returns copy of the string with first letter capitalized" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "msg1 = 'hello'\n", "msg2 = 'Goodbye'\n", "msg3 = 'garfield'\n", "print(msg1.upper())\n", "print(msg2.lower())\n", "print(msg3.capitalize())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Trimming Methods\n", "\n", "* `strip()` -> returns copy of the string with leading and trailing whitespace removed\n", "* `lstrip()` -> returns copy of the string with leading whitespace removed\n", "* `rstrip()` -> returns copy of the string with trailing whitespace removed" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "msg1 = ' 2 spaces at the front and some at the end \\n'\n", "print(msg1)\n", "print(msg1.strip())\n", "print(msg1.lstrip())\n", "print(msg1.rstrip())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For each of these functions, it's also possible to pass in a string\n", "as an argument to indicate which characters should be trimmed from\n", "start and or end of the string. If provided, all combinations of\n", "its values are stripped from the beginning/end." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "msg2 = '-*-*-*-*aaaHELLOzzz*-*-*-*-'\n", "print(msg2.strip('az-*'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Miscellaneous\n", "\n", "* `find(substring)` -> returns lowest index in the string where `substring` starts.\n", " Returns -1 if `substring` is not in the string.\n", "* `rfind(substring)` -> returns highest index in the string where `substring` starts\n", " (aka last occurrence)\n", "* `index(substring)` -> like `find`, except raises `ValueError` when `substring` not found\n", "* `count(substring)` -> returns the number of non-overlapping\n", " occurrences of `substring` in string" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Converting To/From Lists\n", "\n", "Sometimes it's necessary to explicitly go between\n", "a string and a list. More often than not, this is done by creating a\n", "list of words from a string, or by combining a list of words into\n", "a single string.\n", "\n", "* `split()` -> return a list of words in the string by separating on whitespace.\n", " Consecutive whitespace is treated as a single separator\n", "* `join(lst)` -> concatenates all of the strings in `lst`, separated by whatever\n", " string is calling the method\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "msg1 = 'This is the song that never ends\\nit just goes on and on my friends'\n", "lstmsg1 = msg1.split()\n", "print(lstmsg1)\n", "comma_msg1 = ','.join(lstmsg1)\n", "print(comma_msg1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The default is to split the string on whitespace.\n", "It's also possible to specify a certain character\n", "to separate entries. This is often used with other\n", "common delimiters, such as commas." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "header = 'Day,Month,Year'\n", "print(header.split(','))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It's also possible to separate\n", "a string into a list of it's individual characters by typecasting it\n", "to a list. This could be useful if it's necessary to modify a lot\n", "of the characters as you iterate through a string.\n", "It's not necessary, but it can prevent creating many slightly modified\n", "copies of the string in the process of modifying." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "msg1 = 'hello'\n", "print(list(msg1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Formatting\n", "\n", "So far, all of the printing we've been doing is just separating\n", "the different strings or variables we wanted to print by commas\n", "in our call to the print function. This works okay for some\n", "things, but it doesn't that well if we need to output something\n", "nicely. \n", "\n", "To do that, we use the `format` method. The `format` method\n", "is quite powerful, and can be used for formatting as simple\n", "as just inserting values/variables into a string to more\n", "complex formatting of numbers.\n", "\n", "At the simplest, we begin by adding `{}` anywhere in our\n", "string that we would like to insert a value." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "val1 = 5\n", "val2 = 2\n", "msg = '{} / {} = {}'.format(val1, val2, val1/val2)\n", "print(msg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also number the brackets, in which case the number\n", "indicates which argument to format should be substituted.\n", "More often than not, we'd do this if we want one of them\n", "to be inserted more than once." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "msg = '{1} / {0} = {2}'.format(val1, val2, val2/val1)\n", "print(msg)\n", "msg = '({0} / {1}) * ({1} / {0}) = 1'.format(val1, val2)\n", "print(msg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It can be ugly to keep track of these numbers, so we can also\n", "name them. This can be really helpful for long strings with many\n", "values being inserted, particularly if some occur multiple times." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "msg = 'hello {name} are you {emotion} today?'.format(name=\"Alice\", emotion=\"happy\")\n", "print(msg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we want something like a table to output nicely formatted,\n", "we can indicate to pad to a minimum size by adding a `:` and\n", "following it with the minimum number of characters." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "names = ['Alice', 'Bob', 'John']\n", "emotions = ['happy', 'sad', 'content']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('{0:10}|{1:10}'.format('name', 'emotion'))\n", "print('-'*10 + '|' + '-'*10)\n", "for i in range(len(names)):\n", " print('{0:10}|{1:10}'.format(names[i], emotions[i]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are other modifiers that can be added to change alignment of padding.\n", "For example, adding `^` directly after the colon says to center." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('{0:^10}|{1:^10}'.format('name', 'emotion'))\n", "print('-'*10 + '|' + '-'*10)\n", "for i in range(len(names)):\n", " print('{0:^10}|{1:^10}'.format(names[i], emotions[i]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Formatting Numbers\n", "One of the most helpful uses of `format` is that it allows\n", "an easy way of specifying how to format floating point numbers.\n", "For floating point numbers, the brackets would look something\n", "like `{i:w.ps}` where:\n", "* `i` is the index to substitute into this bracket \n", "* `w` is the minimum field width \n", "* `d` is the number of places after the decimal place to show\n", "* `s` is a format specifier (`f` for fixed point, `e` for scientific\n", " notation, and `g` for general which will choose between `e` and\n", " `f` automatically depending on the magnitude of the number).\n", "\n", "Note that you often don't need all of these, many are optional. \n", "The full range of possibilities with `format` is far more\n", "in depth than this and is described in the\n", "[documenation](https://docs.python.org/3.9/library/string.html#formatspec).\n", "If there is a desired output\n", "format you want, it's likely achievable.\n", "\n", "##### Examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "largenum = 1.23944938751e5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This says to use as many places before the decimal as needed,\n", "and to show at least 3 places after the decimal point,\n", "in fixed point notation." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('{0:.3f}'.format(largenum))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "smallnum = 1.2394498e-6" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The next two print the same number, both with a minimum width of 11.\n", "The first example uses scientific notation with 2 places after the decimal point.\n", "Note the spaces to the left of the printed result. The second example uses fixed\n", "point." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('{0:11.2e}'.format(smallnum))\n", "print('{0:11.9f}'.format(smallnum))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }