\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{brianLane} \pdfinfo{ /Title (python.pdf) /Creator (Cheatography) /Author (brianLane) /Subject (Python Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{0571FF} \definecolor{LightBackground}{HTML}{EFF6FF} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Python Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{brianLane} via \textcolor{DarkBackground}{\uline{cheatography.com/35375/cs/11124/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}brianLane \\ \uline{cheatography.com/brianlane} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 20th April, 2017.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{2} \begin{tabularx}{8.4cm}{x{4 cm} x{4 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Строки}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Строка не мутабельный тип} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{} \tn % Row Count 1 (+ 0) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Наличие подстроки в строке} \tn % Row Count 2 (+ 1) % Row 3 \SetRowColor{white} string = 'Python'\{\{nl\}\}'Py' in string & \{\{nl\}\}True \tn % Row Count 4 (+ 2) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Слайсинг} \tn % Row Count 5 (+ 1) % Row 5 \SetRowColor{white} string = 'I like Python!'\{\{nl\}\}\{\{nl\}\}string{[}0{]}\{\{nl\}\}string{[}:1{]}\{\{nl\}\}string{[}0:12{]}\{\{nl\}\}string{[}:-5{]}\{\{nl\}\}string{[}:14{]}\{\{nl\}\}string{[}:{]}\{\{nl\}\}string{[}2:{]} & 14 characters\{\{nl\}\}\{\{nl\}\}'I'\{\{nl\}\}'I'\{\{nl\}\}'I like Pytho'\{\{nl\}\}'I like Py'\{\{nl\}\}'I like Python!'\{\{nl\}\}'I like Python!'\{\{nl\}\}'like Python!' \tn % Row Count 13 (+ 8) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Репликация} \tn % Row Count 14 (+ 1) % Row 7 \SetRowColor{white} "Alice" * 3 & "AliceAliceAlice" \tn % Row Count 15 (+ 1) % Row 8 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Проход по строке в цикле} \tn % Row Count 16 (+ 1) % Row 9 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{for i in "Python":} \tn % Row Count 17 (+ 1) % Row 10 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Raw Strings} \tn % Row Count 18 (+ 1) % Row 11 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{You can place an r before the beginning quotation mark of a string to make it a raw string. A raw string completely ignores all escape characters and prints any backslash that appears in the string:\{\{nl\}\}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}print(r'That is Carol\textbackslash{}'s cat.')\{\{nl\}\}That is Carol\textbackslash{}'s cat.} \tn % Row Count 24 (+ 6) % Row 12 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Multiline Strings with triple Quotes} \tn % Row Count 25 (+ 1) % Row 13 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}print('''Dear Alice,\{\{nl\}\}\{\{nl\}\}I love you!\{\{nl\}\}\{\{nl\}\}Sincerely,\{\{nl\}\}Bob''')\{\{nl\}\}\{\{nl\}\}}}Dear Alice,\{\{nl\}\}\{\{nl\}\}I love you!\{\{nl\}\}\{\{nl\}\}Sincerely,\{\{nl\}\}Bob} \tn % Row Count 29 (+ 4) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{4 cm} x{4 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Списки}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{List is reference type} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} a = {[}1, 2{]}\{\{nl\}\}b = a\{\{nl\}\}a.append(3)\{\{nl\}\}print(b)\{\{nl\}\}\{\{nl\}\}def add(some\_list):\{\{nl\}\}~~some\_list.append("end")\{\{nl\}\}add(a)\{\{nl\}\}print(a)\{\{nl\}\}\{\{nl\}\}import copy\{\{nl\}\}copy.copy(a)\{\{nl\}\}copy.deepcopy(a) & \{\{nl\}\}\{\{nl\}\}\{\{nl\}\}{[}1, 2, 3{]}\{\{nl\}\}\{\{nl\}\}\{\{nl\}\}\{\{nl\}\}\{\{nl\}\}{[}1, 2, 3, "end"{]}\{\{nl\}\}\{\{nl\}\}\{\{nl\}\}\{\{nl\}\}если список содержит вложенные списки \tn % Row Count 12 (+ 11) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Создание пустого списка} \tn % Row Count 13 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{a = {[}{]}\{\{nl\}\}a = list()} \tn % Row Count 14 (+ 1) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Список из кортежа} \tn % Row Count 15 (+ 1) % Row 5 \SetRowColor{white} list(('cat', 'dog', 5)) & {[}'cat', 'dog', 5{]} \tn % Row Count 17 (+ 2) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Репликация} \tn % Row Count 18 (+ 1) % Row 7 \SetRowColor{white} {[}5, 1{]} * 3 & {[}5, 1, 5, 1, 5, 1{]} \tn % Row Count 19 (+ 1) % Row 8 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Конкатенация} \tn % Row Count 20 (+ 1) % Row 9 \SetRowColor{white} a = {[}1, 2, 3{]}\{\{nl\}\}b = {[}3, 4, 5{]}\{\{nl\}\}\{\{nl\}\}a.extend(b)\{\{nl\}\}a += b & \{\{nl\}\}\{\{nl\}\}\{\{nl\}\}{[}1, 2, 3, 3, 4, 5{]}\{\{nl\}\}{[}1, 2, 3, 3, 4, 5{]} \tn % Row Count 24 (+ 4) % Row 10 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Сортировка} \tn % Row Count 25 (+ 1) % Row 11 \SetRowColor{white} a = {[}3, 2, 6, 9, 8{]}\{\{nobreak\}\}\{\{nl\}\}\{\{nl\}\}a.sort()\{\{nl\}\}a.sort(reverse=True)\{\{nl\}\}\{\{nl\}\}a = {[}'a', 'z', 'A', 'Z'{]}\{\{nl\}\}a.sort()\{\{nl\}\}a.sort(key=str.lower) & \{\{nl\}\}\{\{nl\}\}{[}2, 3, 6, 8, 9{]}\{\{nl\}\}{[}9, 8, 6, 3, 2{]}\{\{nl\}\}\{\{nl\}\}\{\{nl\}\}{[}'A', 'Z', 'a', 'z'{]}\{\{nl\}\}{[}'A', 'a', 'Z', 'z'{]}\{\{nl\}\}This causes the sort() function to treat all the items in the list as if they were lowercase without actually changing the values in the list. \tn % Row Count 38 (+ 13) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{4 cm} x{4 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Списки (cont)}} \tn % Row 12 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{\seqsplit{Отрицательный} индекс} \tn % Row Count 1 (+ 1) % Row 13 \SetRowColor{white} a = {[}5, 11{]}\{\{nl\}\}a{[}-1{]} & \{\{nl\}\}11 \tn % Row Count 3 (+ 2) % Row 14 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Кол-во элементов списка} \tn % Row Count 4 (+ 1) % Row 15 \SetRowColor{white} a = {[}3, 3, 3, 3{]}\{\{nl\}\}len(a) & \{\{nl\}\}4 \tn % Row Count 6 (+ 2) % Row 16 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Наличие элемента в списке} \tn % Row Count 7 (+ 1) % Row 17 \SetRowColor{white} a = {[}22, 13{]}\{\{nl\}\}13 in a & \{\{nl\}\}True \tn % Row Count 9 (+ 2) % Row 18 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Удаление элемента списка} \tn % Row Count 10 (+ 1) % Row 19 \SetRowColor{white} a = {[}"cat", "dog", "cat"{]}\{\{nobreak\}\}\{\{nl\}\}a.remove("cat")\{\{nl\}\}del a{[}1{]} & \{\{nl\}\}{[}"dog", "cat"{]}\{\{nl\}\}{[}"dog"{]} \tn % Row Count 14 (+ 4) % Row 20 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Извлечение значений списка} \tn % Row Count 15 (+ 1) % Row 21 \SetRowColor{white} a = {[}3, 2, 1{]}\{\{nl\}\}x, y, z = a\{\{nl\}\}print(x, y, z) & \{\{nl\}\}\{\{nl\}\}3 2 1 \tn % Row Count 18 (+ 3) % Row 22 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Узнать индекс элемента} \tn % Row Count 19 (+ 1) % Row 23 \SetRowColor{white} a = {[}3, 5, 2, 5{]}\{\{nl\}\}a.index(5) & \{\{nl\}\}1 \tn % Row Count 21 (+ 2) % Row 24 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Добавление элемента} \tn % Row Count 22 (+ 1) % Row 25 \SetRowColor{white} a = {[}1, 2{]}\{\{nl\}\}a.append("end")\{\{nl\}\}a.insert(1, 5) & \{\{nl\}\}{[}1, 2, "end"{]}\{\{nl\}\}{[}1, 5, 2, "end"{]} \tn % Row Count 25 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{4 cm} x{4 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Tuples}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Кортеж не мутабельный, в отличие от списка} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{You can use tuples to convey to anyone reading your code that you don't intend for that sequence of values to change. If you need an ordered sequence of values that never changes, use a tuple. A second bene t of using tuples instead of lists is that, because they are immutable and their contents don't change, Python can implement some optimizations that make code using tuples slightly faster than code using lists.} \tn % Row Count 11 (+ 9) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Создание кортежа из одного элемента} \tn % Row Count 13 (+ 2) % Row 3 \SetRowColor{white} a = (1,)\{\{nl\}\}type(a)\{\{nl\}\}\{\{nl\}\}a = (1)\{\{nl\}\}type(a) & \{\{nl\}\}\textless{}class 'tuple'\textgreater{}\{\{nl\}\}\{\{nl\}\}\{\{nl\}\}\textless{}class 'int'\textgreater{} \tn % Row Count 16 (+ 3) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Кортеж из списка} \tn % Row Count 17 (+ 1) % Row 5 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{a = tuple({[}1, 2, 3{]})} \tn % Row Count 18 (+ 1) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Слайсинг} \tn % Row Count 19 (+ 1) % Row 7 \SetRowColor{white} a = (1, 2, 3, 4, 5)\{\{nl\}\}a{[}0:3{]} & \{\{nl\}\}(1, 2, 3) \tn % Row Count 21 (+ 2) % Row 8 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Multiple-assignment trick} \tn % Row Count 22 (+ 1) % Row 9 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{} a = (1, 2, 3)\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{} x, y, z = a\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{} y}}\{\{nl\}\}2} \tn % Row Count 24 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Dictionaries}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Ключи должны быть \seqsplit{иммутабельными} типами} \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{} \tn % Row Count 2 (+ 0) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Создание пустого словаря} \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{a = \{\}\{\{nl\}\}a = dict()} \tn % Row Count 4 (+ 1) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Наличие элемента в словаре} \tn % Row Count 5 (+ 1) % Row 5 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{a = \{"one":1, "two":2\}\{\{nl\}\}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}"one" in a\{\{nl\}\}True\{\{nl\}\}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}3 not in a.values()\{\{nl\}\}True\{\{nl\}\}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}a.setdefault("three", 3)\{\{nl\}\}3\{\{nl\}\}- если в {\bf{a}} есть ключ "three", то возвращает значение по этому ключу, иначе создает пару \{"three":3\} и возвращает 3} \tn % Row Count 12 (+ 7) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Извлечение элементов словаря} \tn % Row Count 14 (+ 2) % Row 7 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{a = \{'one':1, 'two':2\}\{\{nl\}\}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}a.get("three", 0)\{\{nl\}\}0\{\{nl\}\}- безопасное извлечение элемента: если такого ключа нет, то вернется значение второго аргумента get\{\{nl\}\}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}a.items()\{\{nl\}\}dict\_items({[}('two', 2), ('one', 1){]})\{\{nl\}\}\{\{nl\}\}for k, v in a.items():\{\{nl\}\}~~...\{\{nl\}\}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}a.values()\{\{nl\}\}dict\_values({[}2, 1{]})\{\{nl\}\}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}a.keys()\{\{nl\}\}dict\_keys({[}'one', 'two'{]})\{\{nl\}\}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}list(a.keys())\{\{nl\}\}{[}'one', 'two'{]}\{\{nl\}\}\{\{nl\}\}In Python 2, the keys method returns a list. But in Python 3, it returns a view object. This gives the developer the ability to update the dictionary and the view will automatically update too.} \tn % Row Count 29 (+ 15) % Row 8 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Pretty Printing} \tn % Row Count 30 (+ 1) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Dictionaries (cont)}} \tn % Row 9 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{import pprint\{\{nl\}\}\{\{nl\}\}a = \{'one':1, 'two':2\}\{\{nl\}\}pprint.pprint(a)\{\{nl\}\}\{\{nl\}\}If you want to obtain the pretti ed text as a string value instead of dis- playing it on the screen, call pprint.pformat() instead:\{\{nl\}\}\{\{nl\}\}print(pprint.pformat(a))} \tn % Row Count 5 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{4.16 cm} x{3.84 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Conditional \& Loop Statements}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{if\{\{nl\}\}elif\{\{nl\}\}else} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{\textgreater{}, \textgreater{}=, ==, !=, or, and, not} \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{if x not in my\_list:\{\{nl\}\}~~...} \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{0, 0.0, (), {[}{]}, "", None = False} \tn % Row Count 4 (+ 1) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{} \tn % Row Count 4 (+ 0) % Row 5 \SetRowColor{white} break & выход из цикла \tn % Row Count 6 (+ 2) % Row 6 \SetRowColor{LightBackground} continue & \seqsplit{пропустить} итерацию \tn % Row Count 8 (+ 2) % Row 7 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{} \tn % Row Count 8 (+ 0) % Row 8 \SetRowColor{LightBackground} for i in range(5):\{\{nl\}\}~~print(i) & \{\{nl\}\}0, 1, 2, 3, 4 \tn % Row Count 11 (+ 3) % Row 9 \SetRowColor{white} for i in range(5, 10):\{\{nl\}\}~~print(i) & \{\{nl\}\}5,6,7,8,9 \tn % Row Count 14 (+ 3) % Row 10 \SetRowColor{LightBackground} for i in range(5, 10, 2):\{\{nl\}\}~~print(i) & \{\{nl\}\}5, 7, 9 \tn % Row Count 17 (+ 3) % Row 11 \SetRowColor{white} for i in range(5, -1, -1):\{\{nl\}\}~~print(i) & \{\{nl\}\}5, 4, 3, 2, 1, 0 \tn % Row Count 20 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{5.84 cm} x{2.16 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Regular Expressions}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Модуль регэкспов} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{import re}}} \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{-} \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textbackslash{}d}} - stands for a digit character\{\{nl\}\}\{\{nl\}\}333-333-4444:\{\{nl\}\}{\bf{\textbackslash{}d\textbackslash{}d\textbackslash{}d-\textbackslash{}d\textbackslash{}d\textbackslash{}d-\textbackslash{}d\textbackslash{}d\textbackslash{}d\textbackslash{}d}}\{\{nl\}\}or:\{\{nl\}\}{\bf{\textbackslash{}d\{3\}-\textbackslash{}d\{3\}-\textbackslash{}d\{4\}}}\{\{nl\}\}\{\{nl\}\}Passing a string value representing your regular expression to {\bf{re.compile()}} returns a Regex pattern object (or simply, a Regex object).\{\{nl\}\}To create a Regex object that matches the phone number pattern, enter:\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}phoneNumRegex = re.compile(r'\textbackslash{}d\{3\}-\textbackslash{}d\{3\}-\textbackslash{}d\{4\}')}}\{\{nl\}\}- by putting an {\bf{r}} before the first quote of the string value, you can mark the string as a raw string, which does not escape characters.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo = phoneNumRegex.search('My number is 415-555-4242')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo.group()}}\{\{nl\}\}'415-555-4242'\{\{nl\}\}\{\{nl\}\}A Regex object's {\bf{search()}} method searches the string it is passed for any matches to the regex. The {\bf{search()}} method will return {\bf{None}} if the regex pattern is not found in the string. If the pattern is found, the {\bf{search()}} method returns a {\bf{Match object}}. {\bf{Match objects}} have a {\bf{group()}} method that will return the actual matched text from the searched string.} \tn % Row Count 25 (+ 22) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Grouping with Parentheses} \tn % Row Count 26 (+ 1) % Row 5 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{Say you want to separate the area code from the rest of the phone number. Adding parentheses will create groups in the regex: (\textbackslash{}d\textbackslash{}d\textbackslash{}d)-(\textbackslash{}d\textbackslash{}d\textbackslash{}d-\textbackslash{}d\textbackslash{}d\textbackslash{}d\textbackslash{}d). Then you can use the group() match object method to grab the matching text from just one group.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}phoneNumRegex = re.compile(r'(\textbackslash{}d\{3\})-(\textbackslash{}d\{3\}-\textbackslash{}d\{4\})')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo = phoneNumRegex.search('My number is 431-559-2243')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo.group(1)}}\{\{nl\}\}'431'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo.group(2)}}\{\{nl\}\}'559-2243'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo.group(0)}} or {\bf{\textgreater{}\textgreater{}\textgreater{}mo.group()}}\{\{nl\}\}'431-559-2243'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo.groups()}}\{\{nl\}\}('431', '559-2243')\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}areaCode, mainNumber = mo.groups()\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}areaCode}}\{\{nl\}\}'431'\{\{nl\}\}\{\{nl\}\}Parentheses have a special meaning in regular expressions, but what do you do if you need to match a parenthesis in your text? In this case, you need to escape the ( and ) characters with a back-slash:\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}\textgreater{}\textgreater{}\textgreater{}phoneNumRegex = re.compile(r'(\textbackslash{}(\textbackslash{}d\{3\}\textbackslash{})) (\textbackslash{}d\{3\}-\textbackslash{}d\{4\})')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo = phoneNumRegex.search('My phone number is (415) 555-4242.')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo.group(1)}}\{\{nl\}\}'(415)'} \tn % Row Count 47 (+ 21) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{5.84 cm} x{2.16 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Regular Expressions (cont)}} \tn % Row 6 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Matching Multiple Groups with the Pipe} \tn % Row Count 1 (+ 1) % Row 7 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{The | character is called a pipe. You can use it anywhere you want to match one of many expressions. For example, the regular expression r'Batman|Tina Fey' will match either 'Batman' or 'Tina Fey'.\{\{nl\}\}When both Batman and Tina Fey occur in the searched string, the first occurrence of matching text will be returned as the Match object:\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}heroRegex = re.compile(r'Batman|Tina Fey')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1 = heroRegex.search('Batman and Tina Fey.')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1.group()}}\{\{nl\}\}'Batman'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo2 = heroRegex.search('Tina Fey and Batman.')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo2.group()}}\{\{nl\}\}'Tina Fey'\{\{nl\}\}\{\{nl\}\}You can also use the pipe to match one of several patterns as part of your regex. For example, say you wanted to match any of the strings 'Batman', 'Batmobile', 'Batcopter', and 'Batbat'. Since all these strings start with Bat, it would be nice if you could specify that prefix only once:\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}batRegex = re.compile(r'Bat(man|mobile|copter|bat)')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo = \seqsplit{batRegex.search('Batmobile} lost a wheel')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo.group()}}\{\{nl\}\}'Batmobile'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo.group(1)}}\{\{nl\}\}'mobile'\{\{nl\}\}\{\{nl\}\}If you need to match an actual pipe character, escape it with a back- slash, like \textbackslash{}|.} \tn % Row Count 25 (+ 24) % Row 8 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{.findall()} \tn % Row Count 26 (+ 1) % Row 9 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}heroRegex = re.compile(r'Batman|Tina Fey')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}heroRegex.findall('Batman and Tina Fey.')}}\{\{nl\}\}{[}'Batman', 'Tina Fey'{]}\{\{nl\}\}\{\{nl\}\}In addition to the {\bf{search()}} method, {\bf{Regex objects}} also have a {\bf{findall()}} method. While {\bf{search()}} will return a {\bf{Match object}} of the first matched text in the searched string, the {\bf{findall()}} method will return the strings of every match in the searched string.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}phoneNumRegex = re.compile(r'\textbackslash{}d\textbackslash{}d\textbackslash{}d-\textbackslash{}d\textbackslash{}d\textbackslash{}d-\textbackslash{}d\textbackslash{}d\textbackslash{}d\textbackslash{}d')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo = \seqsplit{phoneNumRegex.search('Cell:} 415-555-9999 Work: 212-555-0000')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo.group()}}\{\{nl\}\}'415-555-9999'\{\{nl\}\}\{\{nl\}\}On the other hand, {\bf{findall()}} will not return a {\bf{Match object}} but a list of strings — {\emph{as long as there are no groups in the regular expression}}.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}phoneNumRegex = re.compile(r'\textbackslash{}d\{3\}-\textbackslash{}d\{3\}-\textbackslash{}d\{4\}') \# has no groups\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')}}\{\{nl\}\}{[}'415-555-9999', '212-555-0000'{]}\{\{nl\}\}\{\{nl\}\}If there are groups in the regular expression, then {\bf{findall()}} will return a list of tuples. Each tuple represents a found match, and its items are the matched strings for each group in the regex. Notice that the regular expression being compiled now has groups in parentheses:\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}phoneNumRegex = re.compile(r'(\textbackslash{}d\textbackslash{}d\textbackslash{}d)-(\textbackslash{}d\textbackslash{}d\textbackslash{}d)-(\textbackslash{}d\textbackslash{}d\textbackslash{}d\textbackslash{}d)') \# has groups\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')}}\{\{nl\}\}{[}('415', '555', '1122'), ('212', '555', '0000'){]}} \tn % Row Count 56 (+ 30) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{5.84 cm} x{2.16 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Regular Expressions (cont)}} \tn % Row 10 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Optional Matching with the Question Mark} \tn % Row Count 1 (+ 1) % Row 11 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{Sometimes there is a pattern that you want to match only optionally. That is, the regex should find a match whether or not that bit of text is there. The ? character flags the group that precedes it as an optional part of the pattern:\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}batRegex = re.compile(r'Bat(wo)?man')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1 = batRegex.search('The Adventures of Batman')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1.group()}}\{\{nl\}\}'Batman'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo2 = batRegex.search('The Adventures of Batwoman')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo2.group()}}\{\{nl\}\}'Batwoman'\{\{nl\}\}\{\{nl\}\}or:\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}phoneRegex = re.compile(r'(\textbackslash{}d\textbackslash{}d\textbackslash{}d-)?\textbackslash{}d\textbackslash{}d\textbackslash{}d-\textbackslash{}d\textbackslash{}d\textbackslash{}d\textbackslash{}d')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1 = phoneRegex.search('My number is 415-555-4242')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1.group()}}\{\{nl\}\}'415-555-4242'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo2 = phoneRegex.search('My number is 555-4242')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo2.group()}}\{\{nl\}\}'555-4242'\{\{nl\}\}\{\{nl\}\}You can think of the ? as saying, "Match zero or one of the group pre- ceding this question mark."\{\{nl\}\}If you need to match an actual question mark character, escape it with \textbackslash{}?.} \tn % Row Count 21 (+ 20) % Row 12 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Matching Zero or More with the Star} \tn % Row Count 22 (+ 1) % Row 13 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{The * (called the star or asterisk) means "match zero or more"—the group that precedes the star can occur any number of times in the text. It can be completely absent or repeated over and over again:\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}batRegex = re.compile(r'Bat(wo)*man')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1 = batRegex.search('The Adventures of Batman')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1.group()}}\{\{nl\}\}'Batman'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo2 = batRegex.search('The Adventures of Batwoman')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo2.group()}}\{\{nl\}\}'Batwoman'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo3 = batRegex.search('The Adventures of Batwowowowoman')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo3.group()}}\{\{nl\}\}'Batwowowowoman'} \tn % Row Count 34 (+ 12) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{5.84 cm} x{2.16 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Regular Expressions (cont)}} \tn % Row 14 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Matching One or More with the Plus} \tn % Row Count 1 (+ 1) % Row 15 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{While * means "match zero or more", the + (or plus) means "match one or more." Unlike the star, which does not require its group to appear in the matched string, the group preceding a plus must appear at least once. It is not optional:\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}batRegex = re.compile(r'Bat(wo)+man')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1 = batRegex.search('The Adventures of Batwoman')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1.group()}}\{\{nl\}\}'Batwoman'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo2 = batRegex.search('The Adventures of Batwowowowoman')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo2.group()}}\{\{nl\}\}'Batwowowowoman'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}mo3 = batRegex.search('The Adventures of Batman')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo3 == None}}\{\{nl\}\}True\{\{nl\}\}\{\{nl\}\}If you need to match an actual plus sign character, prefix the plus sign with a backslash to escape it: \textbackslash{}+.} \tn % Row Count 16 (+ 15) % Row 16 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Matching Specific Repetitions with Curly Brackets} \tn % Row Count 17 (+ 1) % Row 17 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{If you have a group that you want to repeat a specific number of times, follow the group in your regex with a number in curly brackets. For example, the regex (Ha)\{3\} will match the string 'HaHaHa', but it will not match 'HaHa', since the latter has only two repeats of the (Ha) group.\{\{nl\}\}Instead of one number, you can specify a range by writing a minimum, a comma, and a maximum in between the curly brackets. For example, the regex (Ha)\{3,5\} will match 'HaHaHa', 'HaHaHaHa', and 'HaHaHaHaHa'.\{\{nl\}\}You can also leave out the first or second number in the curly brackets to leave the minimum or maximum unbounded. For example, (Ha)\{3,\} will match three or more instances of the (Ha) group, while (Ha)\{,5\} will match zero to five instances. Curly brackets can help make your regular expressions shorter.} \tn % Row Count 34 (+ 17) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{5.84 cm} x{2.16 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Regular Expressions (cont)}} \tn % Row 18 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Greedy and Nongreedy Matching} \tn % Row Count 1 (+ 1) % Row 19 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{Since {\bf{(Ha)\{3,5\}}} can match three, four, or five instances of {\bf{Ha}} in the string {\bf{'HaHaHaHaHa'}}, you may wonder why the {\bf{Match object}}'s call to {\bf{group()}} returns {\bf{'HaHaHaHaHa'}} instead of the shorter possibilities. After all, {\bf{'HaHaHa'}} and {\bf{'HaHaHaHa'}} are also valid matches of the regular expression {\bf{(Ha)\{3,5\}}}.\{\{nl\}\}Python's regular expressions are greedy by default, which means that in ambiguous situations they will match the longest string possible. The non- greedy version of the curly brackets, which matches the shortest string pos- sible, has the closing curly bracket followed by a question mark.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}greedyHaRegex = re.compile(r'(Ha)\{3,5\}')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1 = greedyHaRegex.search('HaHaHaHaHa')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo1.group()}}\{\{nl\}\}'HaHaHaHaHa'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}nongreedyHaRegex = re.compile(r'(Ha)\{3,5\}?')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo2 = nongreedyHaRegex.search('HaHaHaHaHa')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo2.group()}}\{\{nl\}\}'HaHaHa'\{\{nl\}\}\{\{nl\}\}Note that the question mark can have two meanings in regular expres- sions: declaring a nongreedy match or flagging an optional group. These meanings are entirely unrelated.} \tn % Row Count 24 (+ 23) % Row 20 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Character Classes} \tn % Row Count 25 (+ 1) % Row 21 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textbackslash{}d}} is shorthand for the regular expression (0|1|2|3|4|5|6|7|8|9)\{\{nl\}\}\{\{nl\}\}{\bf{\textbackslash{}d}}\{\{nl\}\}- any numeric digit from 0 to 9\{\{nl\}\}\{\{nl\}\}{\bf{\textbackslash{}D}}\{\{nl\}\}- any character that is {\bf{not}} a numeric digit from 0 to 9\{\{nl\}\}\{\{nl\}\}{\bf{\textbackslash{}w}}\{\{nl\}\}- any letter, numeric digit, or the underscore character.\{\{nl\}\}\{\{nl\}\}{\bf{\textbackslash{}W}}\{\{nl\}\}- any character that is {\bf{not}} a letter, numeric digit, or the underscore character.\{\{nl\}\}\{\{nl\}\}{\bf{\textbackslash{}s}}\{\{nl\}\}- any space, tab, or newline character.\{\{nl\}\}\{\{nl\}\}{\bf{\textbackslash{}S}}\{\{nl\}\}- any character that is {\bf{not}} a space, tab, or newline.\{\{nl\}\}\{\{nl\}\}{\bf{{[}0-5{]}}}\{\{nl\}\}- this character class will match only the numbers 0 to 5; this is much shorter than typing (0|1|2|3|4|5).\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}xmasRegex = re.compile(r'\textbackslash{}d+\textbackslash{}s\textbackslash{}w+')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}xmasRegex.findall('12 drummers, 110 pipers, 1 lord')}}\{\{nl\}\}{[}'12 drummers', '110 pipers', '1 lord'{]}} \tn % Row Count 42 (+ 17) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{5.84 cm} x{2.16 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Regular Expressions (cont)}} \tn % Row 22 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Making Your Own Character Classes} \tn % Row Count 1 (+ 1) % Row 23 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{There are times when you want to match a set of characters but the shorthand character classes (\textbackslash{}d, \textbackslash{}w, \textbackslash{}s, and so on) are too broad. You can define your own character class using square brackets.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}vowelRegex = re.compile(r'{[}aeiouAEIOU{]}')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}vowelRegex.findall('RoboCop eats baby food. BABY FOOD.')}}\{\{nl\}\}{[}'o', 'o', 'o', 'e', 'a', 'a', 'o', 'o', 'A', 'O', 'O'{]}\{\{nl\}\}\{\{nl\}\}You can also include ranges of letters or numbers by using a hyphen. For example, the character class {\bf{{[}a-zA-Z0-9{]}}} will match all lowercase letters, uppercase letters, and numbers.\{\{nl\}\}\{\{nl\}\}Note that inside the square brackets, the normal regular expression symbols are not interpreted as such. This means you do not need to escape the ., *, ?, or () characters with a preceding backslash. For example, the character class {\bf{{[}0-5.{]}}} will match digits 0 to 5 and a period. You do not need to write it as {\bf{{[}0-5\textbackslash{}.{]}}}.\{\{nl\}\}\{\{nl\}\}By placing a caret character (\textasciicircum{}) just after the character class's opening bracket, you can make a negative character class. A negative character class will match all the characters that are not in the character class.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}consonantRegex = re.compile(r'{[}\textasciicircum{}aeiouAEIOU{]}')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}consonantRegex.findall('RoboCop eats baby food. BABY FOOD.')}}\{\{nl\}\}{[}'R', 'b', 'c', 'p', ' ', 't', 's', ' ', 'b', 'b', 'y', ' ', 'f', 'd', '.', ' ', 'B', 'B', 'Y', ' ', 'F', 'D', '.'{]}} \tn % Row Count 29 (+ 28) % Row 24 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{The Caret and Dollar Sign Characters} \tn % Row Count 30 (+ 1) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{5.84 cm} x{2.16 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Regular Expressions (cont)}} \tn % Row 25 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{{\bf{r'\textasciicircum{}Hello'}} - matches strings that begin with 'Hello', like 'Hello bla' but not 'bla Hello'\{\{nl\}\}\{\{nl\}\}{\bf{r'\textbackslash{}d\$'}} - matches strings that end with a numeric character from 0 to 9, like 'bla3' but not '3bla'\{\{nl\}\}\{\{nl\}\}{\bf{r'\textasciicircum{}\textbackslash{}d+\$'}} - matches strings that completely consist of numbers, like '123456' but not '123abc456'\{\{nl\}\}\{\{nl\}\}{\bf{"Carrots cost dollars"}} - the caret comes first and the dollar sign comes last.} \tn % Row Count 9 (+ 9) % Row 26 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{The Wildcard Character} \tn % Row Count 10 (+ 1) % Row 27 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{The . (or dot) character in a regular expression is called a wildcard and will match any character except for a newline.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}atRegex = re.compile(r'.at')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}atRegex.findall('The cat in the hat sat on the flat mat.')}}\{\{nl\}\}{[}'cat', 'hat', 'sat', 'lat', 'mat'{]}\{\{nl\}\}\{\{nl\}\}To match an actual dot, escape the dot with a backslash: \textbackslash{}.} \tn % Row Count 17 (+ 7) % Row 28 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{Matching Everything with Dot-Star} \tn % Row Count 18 (+ 1) % Row 29 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{{\bf{.* - stands for anything}}\{\{nl\}\}Dot character means "any single character except the newline"\{\{nl\}\}The star character means "zero or more of the preceding character"\{\{nl\}\}\{\{nl\}\}The dot-star uses {\emph{greedy}} mode: It will always try to match as much text as possible. To match any and all text in a {\emph{nongreedy}} fashion, use the dot, star, and question mark (.*?):\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}nongreedyRegex = re.compile(r'\textless{}.*?\textgreater{}')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo = nongreedyRegex.search('\textless{}To serve man\textgreater{} for dinner.\textgreater{}')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo.group()}}\{\{nl\}\}'\textless{}To serve man\textgreater{}'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}greedyRegex = re.compile(r'\textless{}.*\textgreater{}')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}mo = greedyRegex.search('\textless{}To serve man\textgreater{} for dinner.\textgreater{}')\{\{nl\}\}mo.group()}}\{\{nl\}\}'\textless{}To serve man\textgreater{} for dinner.\textgreater{}'} \tn % Row Count 33 (+ 15) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{5.84 cm} x{2.16 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Regular Expressions (cont)}} \tn % Row 30 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Matching Newlines with the Dot Character} \tn % Row Count 1 (+ 1) % Row 31 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{The dot-star will match everything except a newline. By passing {\bf{re.DOTALL}} as the second argument to {\bf{re.compile()}}, you can make the dot character match all characters, including the newline character.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}newlineRegex = re.compile('.*', re.DOTALL)\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}newlineRegex.search('Bla-bla.\textbackslash{}nBla-bla.').group()}}\{\{nl\}\}'Bla-bla.\textbackslash{}nBla-bla.'} \tn % Row Count 9 (+ 8) % Row 32 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Case-Insensitive Matching} \tn % Row Count 10 (+ 1) % Row 33 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{re.IGNORECASE}} or {\bf{re.I}} as a second argument to {\bf{re.compile()}}} \tn % Row Count 12 (+ 2) % Row 34 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Substituting Strings with the sub() Method} \tn % Row Count 13 (+ 1) % Row 35 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}namesRegex = re.compile(r'Agent \textbackslash{}w+')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')}}\{\{nl\}\}'CENSORED gave the secret documents to CENSORED.'\{\{nl\}\}\{\{nl\}\}Sometimes you may need to use the matched text itself as part of the substitution. In the first argument to {\bf{sub()}}, you can type {\bf{\textbackslash{}1}}, {\bf{\textbackslash{}2}}, {\bf{\textbackslash{}3}}, and so on, to mean "Enter the text of group 1, 2, 3, and so on, in the substitution."\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}agentNamesRegex = re.compile(r'Agent (\textbackslash{}w)\textbackslash{}w*')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}agentNamesRegex.sub(r'\textbackslash{}1****', 'Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.')}}\{\{nl\}\}A**** told C**** that E**** knew B**** was a double agent.'} \tn % Row Count 28 (+ 15) % Row 36 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Managing Complex Regexes} \tn % Row Count 29 (+ 1) % Row 37 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{Regular expressions are fine if the text pattern you need to match is simple. But matching complicated text patterns might require long, convoluted regular expressions. You can mitigate this by telling the {\bf{re.compile()}} function to ignore whitespace and comments inside the regular expression string. This "verbose mode" can be enabled by passing the variable {\bf{re.VERBOSE}} as the second argument to {\bf{re.compile()}}:} \tn % Row Count 38 (+ 9) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{x{5.84 cm} x{2.16 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Regular Expressions (cont)}} \tn % Row 38 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{{\bf{phoneRegex = re.compile(r'''(}}} \tn % Row Count 1 (+ 1) % Row 39 \SetRowColor{white} ~~~~{\bf{(\textbackslash{}d\{3\}|\textbackslash{}(\textbackslash{}d\{3\}\textbackslash{}))?}} & \# area code \tn % Row Count 3 (+ 2) % Row 40 \SetRowColor{LightBackground} ~~~~{\bf{(\textbackslash{}s|-|\textbackslash{}.)?}} & \# separator \tn % Row Count 5 (+ 2) % Row 41 \SetRowColor{white} ~~~~{\bf{(\textbackslash{}s*(ext|x|ext.)\textbackslash{}s*\textbackslash{}d\{2,5\})?}}\{\{nobreak\}\} & \# extension \tn % Row Count 8 (+ 3) % Row 42 \SetRowColor{LightBackground} ~~~~{\bf{\textbackslash{}d\{4\}}} & \# last 4 digits \tn % Row Count 10 (+ 2) % Row 43 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{)''', re.VERBOSE)}}} \tn % Row Count 11 (+ 1) % Row 44 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Combining re.IGNORECASE, re.DOTALL, and re.VERBOSE} \tn % Row Count 12 (+ 1) % Row 45 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}someRegexValue = re.compile('foo', re.IGNORECASE | re.DOTALL | re.VERBOSE)}}} \tn % Row Count 14 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{String Methods}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Длина строки} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{len({\bf{string}})} \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Заглавные, строчные} \tn % Row Count 3 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{string}} = 'aLpHa4'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}string.upper()}}\{\{nl\}\}'ALPHA4'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}string.isupper()}}\{\{nl\}\}True\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}string.lower()}}\{\{nl\}\}'alpha4'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}string.islower()}}\{\{nl\}\}True\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}string = '4'}} or {\bf{'Hello'}}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}string.islower()}} or {\bf{isupper()}}\{\{nl\}\}False\{\{nl\}\}\{\{nl\}\}The upper() and lower() methods are helpful if you need to make a case-insensitive comparison. The strings 'great' and 'GREat' are not equal to each other. But in the following small program, it does not matter whether the user types Great, GREAT, or grEAT, because the string is first converted to lowercase.\{\{nl\}\}\{\{nl\}\}} \tn % Row Count 16 (+ 13) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Все методы типа String в виде списка строк} \tn % Row Count 18 (+ 2) % Row 5 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{dir({\bf{string}})} \tn % Row Count 19 (+ 1) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Справка по методу} \tn % Row Count 20 (+ 1) % Row 7 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{help({\bf{string}}.capitalize)} \tn % Row Count 21 (+ 1) % Row 8 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Уникальный ID объекта} \tn % Row Count 22 (+ 1) % Row 9 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{id({\bf{string}})} \tn % Row Count 23 (+ 1) % Row 10 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{The isX String Methods} \tn % Row Count 24 (+ 1) % Row 11 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{.isalpha()}}\{\{nl\}\}returns True if the string consists only of letters and is not blank.\{\{nl\}\}{\bf{'hello'}} - True\{\{nl\}\}{\bf{'hello123'}} - False\{\{nl\}\}\{\{nl\}\}{\bf{.isalnum()}}\{\{nl\}\}returns True if the string consists only of letters and numbers and is not blank.\{\{nl\}\}{\bf{'hello123', 'hello', '123'}} - True\{\{nl\}\}\{\{nl\}\}{\bf{.isdecimal()}}\{\{nl\}\}returns True if the string consists only of numeric characters and is not blank.\{\{nl\}\}{\bf{'123'}} - True\{\{nl\}\}\{\{nl\}\}{\bf{.isspace()}}\{\{nl\}\}returns True if the string consists only of spaces, tabs, and new- lines and is not blank.\{\{nl\}\}{\emph{'~~~~'}} - True\{\{nl\}\}\{\{nl\}\}{\bf{.istitle()}}\{\{nl\}\}returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase letters.\{\{nl\}\}{\bf{'This Is Title Case'\{\{nl\}\}'This Is Title Case 123'}} - True\{\{nl\}\}\{\{nl\}\}{\bf{'This Is not Title Case'\{\{nl\}\}'This Is NOT Title Case Either'}} - False} \tn % Row Count 43 (+ 19) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{String Methods (cont)}} \tn % Row 12 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Содержит начало/конец?} \tn % Row Count 1 (+ 1) % Row 13 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}'Hello world!'.startswith('Hello')}}\{\{nl\}\}True\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}'Hello world!'.endswith('world!')}}\{\{nl\}\}True} \tn % Row Count 4 (+ 3) % Row 14 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{\seqsplit{Объединение/разбиение} строк} \tn % Row Count 6 (+ 2) % Row 15 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{ \textgreater{}\textgreater{}\textgreater{}' | '.join({[}'cats', 'rats', 'bats'{]})}}\{\{nl\}\}'cats | rats | bats'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}'My name is Clark'.split()}}\{\{nl\}\}{[}'My', 'name', 'is', 'Clark'{]}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}'MyABCnameABCisABCClark'.split('ABC')}}\{\{nl\}\}{[}'My', 'name', 'is', 'Clark'{]}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}'My name is Clark'.split('m')}}\{\{nl\}\}{[}'My na', 'e is Clark'{]}\{\{nl\}\}\{\{nl\}\}A common use of split() is to split a multiline string along the newline characters:\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}str = '''Dear Alice,\{\{nl\}\}bla-bla\{\{nl\}\}Sincerely,\{\{nl\}\}Bob'''\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}str.split('\textbackslash{}n')}}\{\{nl\}\}{[}'Dear Alice,', 'bla-bla', 'Sincerely,', 'Bob'{]}} \tn % Row Count 18 (+ 12) % Row 16 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Выравнивание текста} \tn % Row Count 19 (+ 1) % Row 17 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}'Hello'.rjust(10)}}\{\{nl\}\}'~~~~~~~Hello'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}'Hello'.rjust(10, '*')}}\{\{nl\}\}'*****Hello'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}'Hello'.ljust(10)}}\{\{nl\}\}'Hello~~~~~~~'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}'Hello'.center(15)}}\{\{nl\}\}'~~~~~Hello~~~~~'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}'Hello'.center(15, '=')}}\{\{nl\}\}'=====Hello====='} \tn % Row Count 27 (+ 8) % Row 18 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Удаление пробелов} \tn % Row Count 28 (+ 1) % Row 19 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}'~~~~~Hello World~~~~~'.strip()}}\{\{nl\}\}'Hello World'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}'~~~~~Hello World~~~~~'.lstrip()}}\{\{nl\}\}'Hello World~~~~~'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}'~~~~~Hello World~~~~~'.rstrip()}}\{\{nl\}\}'~~~~~Hello World'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}'SpamSpamBaconSpamEggsSpamSpam'.strip('ampS')}}\{\{nl\}\}'BaconSpamEggs'\{\{nl\}\}Passing strip() the argument 'ampS' will tell it to strip occurences of a, m, p, and capital S from the ends of the string stored in spam. The order of the characters in the string passed to strip() does not matter: strip('ampS') will do the same thing as strip('mapS') or strip('Spam').} \tn % Row Count 44 (+ 16) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{String Methods (cont)}} \tn % Row 20 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Доступ к буферу обмена} \tn % Row Count 1 (+ 1) % Row 21 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{The pyperclip module has copy() and paste() functions that can send text to and receive text from your computer's clipboard. Sending the output of your program to the clipboard will make it easy to paste it to an email, word processor, or some other software. Pyperclip does not come with Python. To install it, follow the directions for installing third-party modules in Appendix A.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}import pyperclip\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}pyperclip.copy('Hello world')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}pyperclip.paste()}}\{\{nl\}\}'Hello world'\{\{nl\}\}\{\{nl\}\}Of course, if something outside of your program changes the clipboard contents, the paste() function will return it.} \tn % Row Count 14 (+ 13) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{4.72 cm} x{3.28 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{String Formatting}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{\%i, \%f, \%s - integer, float, string} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} var = "cookies"\{\{nl\}\}"I like \%s" \% var & \{\{nl\}\}"I like cookies" \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} "I like \%s and \%s" \% (var, var)\{\{nobreak\}\} & "I like cookies and cookies" \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} "\%.2f" \% 1.237 & "1.24" \tn % Row Count 6 (+ 1) % Row 4 \SetRowColor{LightBackground} "\%(a)s \%(a)s" \% \{"a":"cat"\}\{\{nobreak\}\} & "cat cat" \tn % Row Count 8 (+ 2) % Row 5 \SetRowColor{white} "\{1\}, \{0\}, \{2\}".format("a", "b", "c")\{\{nobreak\}\} & "b, a, c" \tn % Row Count 11 (+ 3) % Row 6 \SetRowColor{LightBackground} xy = \{"x":2, "y":5\}\{\{nl\}\}"\{x\}, \{y\}".format(**xy) & \{\{nl\}\}"2, 5" \tn % Row Count 14 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{bla}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{\# Python 2.x code\{\{nl\}\}{\bf{a}} = raw\_input("Enter a number: ")\{\{nl\}\}\{\{nl\}\}Возвращает строку с введеными данными\{\{nl\}\}Python 2.x actually has a built-in called input as well; however it tries to execute what is entered as a Python expression whereas raw\_input returns a string.} \tn % Row Count 7 (+ 7) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{\# Python 3.x code\{\{nl\}\}{\bf{a}} = input("Enter a number: ")\{\{nobreak\}\}} \tn % Row Count 9 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{4 cm} x{4 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{random module}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{import random, sys, os, math} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \{\{nl\}\}random.randint(1, 10)\{\{nobreak\}\}\{\{nl\}\}~ & \{\{nl\}\}random int {[}1, 10{]} \tn % Row Count 4 (+ 3) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{\{\{nl\}\}from random import *\{\{nl\}\}\{\{nl\}\}{\emph{With this form of import statement, calls to functions in random will not need the {\bf{random.}} prefix. However, using the full name makes for more readable code, so it is better to use the normal form of the import statement.}}} \tn % Row Count 10 (+ 6) % Row 3 \SetRowColor{white} \{\{nl\}\}sys.exit()\{\{nl\}\}~ & \{\{nl\}\}досрочное \seqsplit{завершение} программы \tn % Row Count 14 (+ 4) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}s = list(range(5))\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}random.shuffle(s)\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}s}}\{\{nl\}\}{[}3, 4, 1, 0, 2{]}} \tn % Row Count 16 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{4.48 cm} x{3.52 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{идф}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{`\textgreater{}\textgreater{}\textgreater{}None == print()\{\{nl\}\}True`\{\{nl\}\}Питон требует чтобы каждая функция возвращала значение и если мы не пишем {\bf{return}}, то Питон за нас добавляет {\bf{return None}}.} \tn % Row Count 5 (+ 5) % Row 1 \SetRowColor{white} print("Hello", end="")\{\{nl\}\}print("World") & HelloWorld \tn % Row Count 7 (+ 2) % Row 2 \SetRowColor{LightBackground} print("a", "b", "c", sep="/") & a/b/c \tn % Row Count 9 (+ 2) % Row 3 \SetRowColor{white} `a = 1\{\{nl\}\}def func():\{\{nl\}\}~~global a\{\{nl\}\}~~a = 2\{\{nl\}\}func()\{\{nl\}\}print(a)` & \{\{nl\}\}\{\{nl\}\}\{\{nl\}\}\{\{nl\}\}\{\{nl\}\}2 \tn % Row Count 14 (+ 5) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{`def func(d):\{\{nl\}\}~~try:\{\{nl\}\}~~~~return 42 / d\{\{nl\}\}~~except ZeroDivisionError:\{\{nl\}\}~~~~print("Error: Invalid argument.")`} \tn % Row Count 18 (+ 4) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Запуск программ в bash}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Shebang line} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{macOS\{\{nl\}\}{\bf{\#! /usr/bin/env python3}}\{\{nl\}\}\{\{nl\}\}Linux\{\{nl\}\}{\bf{\#! /usr/bin/python3}}} \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Run} \tn % Row Count 4 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{To run your Python programs, save your .py file to your home folder. Then, change the .py file's permissions to make it executable:\{\{nl\}\}{\bf{chmod +x pythonScript.py}}\{\{nl\}\}\{\{nl\}\}Run your script by entering:\{\{nl\}\}{\bf{./pythonScript.py}}} \tn % Row Count 9 (+ 5) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Running Python Programs with Assertions Disabled} \tn % Row Count 10 (+ 1) % Row 5 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{You can disable the assert statements in your Python programs for a slight performance improvement. When running Python from the terminal, include the -O switch after python or python3 and before the name of the .py file. This will run an optimized version of your program that skips the assertion checks.} \tn % Row Count 17 (+ 7) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{PIP}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{The pip Tool} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{Beyond the standard library of modules packaged with Python, other developers have written their own modules to extend Python's capabilities even further. The primary way to install third-party modules is to use Python's pip tool. This tool securely downloads and installs Python modules onto your computer from https://pypi.python.org/, the website of the Python Software Foundation. PyPI, or the Python Package Index, is a sort of free app store for Python modules.\{\{nl\}\}The executable file for the pip tool is called pip on Windows and pip3 on OS X and Linux. You can find pip on:\{\{nl\}\}{\bf{macOS}}\{\{nl\}\}/Library/Frameworks/Python.framework/Versions/3.4/bin/pip3\{\{nl\}\}{\bf{Linux}}\{\{nl\}\}/usr/bin/pip3\{\{nl\}\}\{\{nl\}\}While pip comes automatically installed with Python 3.4 on Windows and OS X, you must install it separately on Linux. To install pip3 on:\{\{nl\}\}Ubuntu or Debian Linux:\{\{nl\}\}{\bf{\$ sudo apt-get install python3-pip}}\{\{nl\}\}Fedora Linux:\{\{nl\}\}{\bf{\$ sudo yum install python3 -pip}}} \tn % Row Count 21 (+ 20) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Установка модуля} \tn % Row Count 22 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{macOS, Linux:\{\{nl\}\}{\bf{\$ sudo pip3 install ModuleName}}\{\{nl\}\}\{\{nl\}\}If you already have the module installed but would like to upgrade it to the latest version available on PyPI, run:\{\{nl\}\}{\bf{\$ pip3 install –U ModuleName}}} \tn % Row Count 27 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Working with Files}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Модуль} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{import os\{\{nl\}\}os.path - module inside the os module\{\{nl\}\}\{\{link="http://docs.python.org/3/library/os.path.html"\}\}os.path documentation\{\{/link\}\}} \tn % Row Count 4 (+ 3) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{/ - macOS, Linux; \textbackslash{} - Windows} \tn % Row Count 5 (+ 1) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{If you want your programs to work on all operating systems:\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.join('usr', 'bin', 'spam')}}\{\{nl\}\}'usr/bin/spam' (macOS, Linux)\{\{nl\}\}'usr\textbackslash{}\textbackslash{}bin\textbackslash{}\textbackslash{}spam' (Windows, \textbackslash{}\textbackslash{}- escaped backslash)} \tn % Row Count 10 (+ 5) % Row 4 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{The Current Working Directory} \tn % Row Count 11 (+ 1) % Row 5 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}os.getcwd()}}\{\{nl\}\}'/Users/Admin/Documents'\{\{nl\}\}\{\{nl\}\}Change Directory:\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.chdir('../Movies')}}\{\{nl\}\}\{\{nl\}\}Make Directory:\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.makedirs('./python')}}} \tn % Row Count 15 (+ 4) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Handling Absolute and Relative Paths} \tn % Row Count 16 (+ 1) % Row 7 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.abspath('./Anki')}}\{\{nl\}\}'/Users/Admin/Documents/Anki'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.isabs('..')}}\{\{nl\}\}False\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.relpath('/Users', '/Library/Audio')}}\{\{nl\}\}'../../Users'\{\{nl\}\}\{\{nl\}\}basename - все что после последнего слеша:\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.basename('/Users/Admin')}}\{\{nl\}\}'Admin'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.basename('/Users/Admin/')}}\{\{nl\}\}''\{\{nl\}\}\{\{nl\}\}dirname - до последнего слеша:\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.dirname('/Users/Admin')}}\{\{nl\}\}'Users'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.dirname('/Users/Admin/')}}\{\{nl\}\}'/Users/Admin'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.split('/home/rob/script.py')}}\{\{nl\}\}('/home/rob', 'script.py')\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.sep}} or {\bf{\textgreater{}\textgreater{}\textgreater{}os.path.sep}}\{\{nl\}\}'/'\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}'/home/rob/script.py'.split(os.sep)}}\{\{nl\}\}{[}'', 'home', 'rob', 'script.py'{]}\{\{nl\}\}- on OS X and Linux systems, there will be a blank string at the start of the returned list} \tn % Row Count 34 (+ 18) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Working with Files (cont)}} \tn % Row 8 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Finding File Sizes and Folder Contents} \tn % Row Count 1 (+ 1) % Row 9 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.getsize('/home/rob/text.txt')}}\{\{nl\}\}149\{\{nl\}\}- размер файла в байтах (для папок не работает)\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.listdir('/Users/Admin/a/')}}\{\{nl\}\}{[}'.DS\_Store', 'c', 'dir-tree.list', 'file.txt', 'jupyter'{]}\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.exists('/Users')}}\{\{nl\}\}True\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.isdir('/Users')}}\{\{nl\}\}True\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}os.path.isfile('/Users')}}\{\{nl\}\}False\{\{nl\}\}} \tn % Row Count 10 (+ 9) % Row 10 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Open File} \tn % Row Count 11 (+ 1) % Row 11 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\emph{Plaintext files}} contain only basic text characters and do not include font, size, or color information. Your programs can easily read the contents of plaintext files and treat them as an ordinary string value.\{\{nl\}\}\{\{nl\}\}{\emph{Binary files}} are files such as word processing documents, PDFs, images, spreadsheets, and executable programs. If you open a binary file in Notepad or TextEdit, it will look like scrambled nonsense.\{\{nl\}\}\{\{nl\}\}Open file in {\emph{read mode}}:\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}helloFile = open('./hello.txt', 'r')}}\{\{nl\}\}or\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}helloFile = open('./hello.txt')}}\{\{nl\}\}- open() returns a File object. A File object represents a file on your computer; it is simply another type of value in Python, much like the lists and dictionaries. You can call methods on the File object if you want read or write to the file.} \tn % Row Count 28 (+ 17) % Row 12 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Read File} \tn % Row Count 29 (+ 1) % Row 13 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{{\bf{\textgreater{}\textgreater{}\textgreater{}helloContent = helloFile.read()\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}helloContent}}\{\{nl\}\}'Hello world!'\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}sonnetFile = open('sonnet29.txt')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}sonnetFile.readlines()}}\{\{nl\}\}{[}'first line\textbackslash{}n', 'second line.'{]}\{\{nl\}\}\{\{nl\}\}Note that each of the string values ends with a newline character, \textbackslash{}n , except for the last line of the file.} \tn % Row Count 36 (+ 7) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Working with Files (cont)}} \tn % Row 14 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Write File} \tn % Row Count 1 (+ 1) % Row 15 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{Write mode will overwrite the existing file and start from scratch. Append mode will append text to the end of the existing file.\{\{nl\}\}\{\{nl\}\}If the filename passed to open() does not exist, both write and append mode will create a new, blank file. After reading or writing a file, call the close() method before opening the file again.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}baconFile = open('bacon.txt', 'w')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}baconFile.write('Hello world!\textbackslash{}n')}}\{\{nl\}\}13\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}baconFile.close()\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}baconFile = open('bacon.txt', 'a')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}baconFile.write('Bacon is not a vegetable.')}}\{\{nl\}\}25\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}baconFile.close()\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}baconFile = open('bacon.txt')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}content = baconFile.read()\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}baconFile.close()\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}print(content)}}\{\{nl\}\}Hello world!\{\{nl\}\}Bacon is not a vegetable.\{\{nl\}\}\{\{nl\}\}Note that the write() method does not automatically add a newline character to the end of the string like the print() function does. You will have to add this character yourself.} \tn % Row Count 21 (+ 20) % Row 16 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Saving Variables with the shelve Module} \tn % Row Count 22 (+ 1) % Row 17 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{The shelve module will let you add Save and Open features to your program. For example, if you ran a program and entered some configuration settings, you could save those settings to a shelf file and then have the program load them the next time it is run.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}import shelve\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}shelfFile = shelve.open('mydata')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}cats = {[}'Zophie', 'Pooka'{]}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}shelfFile{[}'cats'{]} = cats\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}shelfFile.close()}}\{\{nl\}\}\{\{nl\}\}After running the previous code on Windows, you will see three new files in the current working directory: mydata.bak, mydata.dat, and mydata.dir. On OS X, only a single mydata.db file will be created. These binary files contain the data you stored in your shelf.\{\{nl\}\}\{\{nl\}\}Shelf values don't have to be opened in read or write mode—they can do both once opened.\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}shelfFile = shelve.open('mydata')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}type(shelfFile)}}\{\{nl\}\}\textless{}class 'shelve.DbfilenameShelf'\textgreater{}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}shelfFile{[}'cats'{]}}}\{\{nl\}\}{[}'Zophie', 'Pooka'{]}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}shelfFile.close()}}\{\{nl\}\}\{\{nl\}\}Just like dictionaries, shelf values have keys() and values() methods that will return list-like values of the keys and values in the shelf. Since these methods return list-like values instead of true lists, you should pass them to the list() function to get them in list form:\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}shelfFile = shelve.open('mydata')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}list(shelfFile.keys())}}\{\{nl\}\}{[}'cats'{]}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}list(shelfFile.values())}}\{\{nl\}\}{[}{[}'Zophie', 'Pooka'{]}{]}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}shelfFile.close()}}\{\{nl\}\}\{\{nl\}\}Plaintext is useful for creating files that you'll read in a text editor such as Notepad or TextEdit, but if you want to save data from your Python pro- grams, use the shelve module.} \tn % Row Count 56 (+ 34) \end{tabularx} \par\addvspace{1.3em} \vfill \columnbreak \begin{tabularx}{8.4cm}{p{0.8 cm} p{0.8 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Working with Files (cont)}} \tn % Row 18 \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Saving Variables with the pprint.pformat() function} \tn % Row Count 2 (+ 2) % Row 19 \SetRowColor{white} \mymulticolumn{2}{x{8.4cm}}{The pprint.pformat() function returns a string formatted as syntactically correct Python code. \{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}import pprint\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}cats = {[}\{'name': 'Zophie', 'desc': 'chubby'\}, \{'name': 'Pooka', 'desc': 'fluffy'\}{]}\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}fileObj = open('myCats.py', 'w')\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}fileObj.write('cats = ' + pprint.pformat(cats) + '\textbackslash{}n')}}\{\{nl\}\}83\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}fileObj.close()}}\{\{nl\}\}\{\{nl\}\}The modules that an import statement imports are themselves just Python scripts. When the string from pprint.pformat() is saved to a .py file, the file is a module that can be imported just like any other.\{\{nl\}\}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}import myCats\{\{nl\}\}\textgreater{}\textgreater{}\textgreater{}myCats.cats}}\{\{nl\}\}{[}\{'name': 'Zophie', 'desc': 'chubby'\}, \{'name': 'Pooka', 'desc': 'fluffy'\}{]}\{\{nl\}\}{\bf{\textgreater{}\textgreater{}\textgreater{}myCats.cats{[}0{]}{[}'name'{]}}}\{\{nl\}\}'Zophie'\{\{nl\}\}\{\{nl\}\}The benefit of creating a .py file (as opposed to saving variables with the shelve module) is that because it is a text file, the contents of the file can be read and modified by anyone with a simple text editor. For most applications, however, saving data using the shelve module is the preferred way to save variables to a file. Only basic data types such as integers, floats, strings, lists, and dictionaries can be written to a file as simple text. File objects, for example, cannot be encoded as text.} \tn % Row Count 28 (+ 26) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Folder names and filenames are not case sensitive on Windows and OS X, they are case sensitive on Linux.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}