{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Strings\n", "\n", "Much of the world's data is text, and a piece of text represented in a computer is called a *string*. A string can represent a word, a sentence, or even the contents of every book in a library. Since text can include numbers (like this: 5) or truth values (True), a string can also describe those things.\n", "\n", "The meaning of an expression depends both upon its structure and the types of values that are being combined. So, for instance, adding two strings together produces another string. This expression is still an addition expression, but it is combining a different type of value." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'datascience'" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"data\" + \"science\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Addition is completely literal; it combines these two strings together without regard for their contents. It doesn't add a space because these are different words; that's up to the programmer (you) to specify." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'data science'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"data\" + \" \" + \"science\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Single and double quotes can both be used to create strings: `'hi'` and `\"hi\"` are identical expressions. Double quotes are often preferred because they allow you to include apostrophes inside of strings." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"This won't work with a single-quoted string!\"" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"This won't work with a single-quoted string!\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Why not? Try it out." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `str` function returns a string representation of any value. Using this function, strings can be constructed that have embedded values." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"That's 2 True\"" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"That's \" + str(1 + 1) + ' ' + str(True)" ] } ], "metadata": { "anaconda-cloud": {}, "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.5" } }, "nbformat": 4, "nbformat_minor": 2 }