From 73d6c20191bf4ee30fcfc88789967fca8b6199ef Mon Sep 17 00:00:00 2001 From: Abhijit-Moholkar <89727322+Abhijit-Moholkar@users.noreply.github.com> Date: Thu, 21 Oct 2021 11:08:01 +0530 Subject: [PATCH 1/2] Add files via upload Enhanced code is added --- 01-Lists.ipynb | 510 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 510 insertions(+) create mode 100644 01-Lists.ipynb diff --git a/01-Lists.ipynb b/01-Lists.ipynb new file mode 100644 index 0000000..2e3d96c --- /dev/null +++ b/01-Lists.ipynb @@ -0,0 +1,510 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lists\n", + "\n", + "List is a collection data type which is ordered and mutable. Unlike Sets, Lists allow duplicate elements.\n", + "They are useful for preserving a sequence of data and further iterating over it. Lists are created with square brackets.\n", + "\n", + "`my_list = [\"banana\", \"cherry\", \"apple\"]`\n", + "\n", + "#### Comparison of basic built-in collection data types in Python:\n", + "\n", + "- List is a collection which is ordered and mutable. Allows duplicate members.\n", + "- Tuple is a collection which is ordered and immutable. Allows duplicate members.\n", + "- Set is a collection which is unordered and unindexed. No duplicate members.\n", + "- Dictionary is a collection which is unordered, mutable and indexed. No duplicate members.\n", + "- Strings are immutable sequences of Unicode code points." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Creating a list\n", + "Lists are created with square brackets or the built-in list function." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['banana', 'cherry', 'apple']\n", + "[]\n", + "[5, True, 'apple']\n", + "[0, 0, 1, 1]\n" + ] + } + ], + "source": [ + "list_1 = [\"banana\", \"cherry\", \"apple\"]\n", + "print(list_1)\n", + "\n", + "# Or create an empty list with the list function\n", + "list_2 = list()\n", + "print(list_2)\n", + "\n", + "# Lists allow different data types\n", + "list_3 = [5, True, \"apple\"]\n", + "print(list_3)\n", + "\n", + "# Lists allow duplicates\n", + "list_4 = [0, 0, 1, 1]\n", + "print(list_4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Access elements\n", + "You access the list items by referring to the index number. Note that the indices start at 0." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "banana\n", + "apple\n" + ] + } + ], + "source": [ + "item = list_1[0]\n", + "print(item)\n", + "\n", + "# You can also use negative indexing, e.g -1 refers to the last item,\n", + "# -2 to the second last item, and so on\n", + "item = list_1[-1]\n", + "print(item)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Access Multiple Element\n", + "To access multiple elements use slicing/" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[10, (20, 30), 'apple', True]\n", + "[10, (20, 30), 'apple', True]\n", + "[10, (20, 30), 'apple', True]\n", + "[(20, 30), 'apple', True]\n", + "[(20, 30), 'apple', True]\n", + "[(20, 30), 'apple']\n", + "[(20, 30), 'apple']\n", + "[10, 'apple']\n", + "[10, 'apple']\n" + ] + } + ], + "source": [ + "list1 = [10,(20,30),'apple' ,True]\n", + "print(list1) # To access all elements of list\n", + "print(list1[::]) # To access all elements of list, because default start is 0, end is n-1 and step is 1\n", + "print(list1[-4::]) # To access all elements of list, starting from -n, -1 and step is 1\n", + "print(list1[1:]) # To access all elements of list excluding first\n", + "print(list1[-3:]) # To access all elements of list excluding first using negative indexing\n", + "print(list1[1:3]) # To access elements of list at index 1,2 as end is excluding\n", + "print(list1[-3:-1]) # To access elements of list at index -3,-2 as end is excluding\n", + "print(list1[::2]) # To access alternate elements of list as stepping is 2\n", + "print(list1[-4::2]) # To access alternate elements of list as stepping is 2 using negative indexing" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Change items\n", + "Just refer to the index number and assign a new value." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['banana', 'cherry', 'lemon']\n" + ] + } + ], + "source": [ + "# Lists can be altered after their creation\n", + "list_1[2] = \"lemon\"\n", + "print(list_1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Change multiple elements of list\n", + "To change multiple elements of list just refere their indices uding slicing and assign new value" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['banana', 'cherry', 'Morning', 'Everybody']\n" + ] + } + ], + "source": [ + "list_1[2:] = ['Morning','Everybody']\n", + "print(list_1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Useful methods\n", + "Have a look at the Python Documentation to see all list methods: \n", + "https://docs.python.org/3/tutorial/datastructures.html " + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Length: 3\n", + "['banana', 'blueberry', 'cherry', 'apple', 'orange']\n", + "Popped item: orange\n", + "['banana', 'blueberry', 'apple']\n", + "[]\n", + "Reversed: ['apple', 'cherry', 'banana']\n", + "Reversed: ['banana', 'cherry', 'apple']\n", + "Sorted: ['apple', 'banana', 'cherry']\n", + "[0, 0, 0, 0, 0]\n", + "[0, 0, 0, 0, 0, 'banana', 'cherry', 'apple']\n", + "['H', 'e', 'l', 'l', 'o']\n" + ] + } + ], + "source": [ + "my_list = [\"banana\", \"cherry\", \"apple\"]\n", + "\n", + "# len() : get the number of elements in a list\n", + "print(\"Length:\", len(my_list))\n", + "\n", + "# append() : adds an element to the end of the list\n", + "my_list.append(\"orange\")\n", + "\n", + "# insert() : adds an element at the specified position\n", + "my_list.insert(1, \"blueberry\")\n", + "print(my_list)\n", + "\n", + "# pop() : removes and returns the item at the given position, default is the last item\n", + "item = my_list.pop()\n", + "print(\"Popped item: \", item)\n", + "\n", + "# remove() : removes an item from the list\n", + "my_list.remove(\"cherry\") # Value error if not in the list\n", + "print(my_list)\n", + "\n", + "# clear() : removes all items from the list\n", + "my_list.clear()\n", + "print(my_list)\n", + "\n", + "# reverse() : reverse the items\n", + "my_list = [\"banana\", \"cherry\", \"apple\"]\n", + "my_list.reverse()\n", + "print('Reversed: ', my_list)\n", + "\n", + "# reversed() : reverse the elements of list. This changes are not inplace. It will create a new object. It is a inbuilt library function.\n", + "my_list = [\"banana\", \"cherry\", \"apple\"]\n", + "reversed(my_list)\n", + "print('Reversed: ', my_list)\n", + "\n", + "# sort() : sort items in ascending order\n", + "my_list.sort()\n", + "print('Sorted: ', my_list)\n", + "\n", + "# use sorted() to get a new list, and leave the original unaffected.\n", + "# sorted() works on any iterable type, not just lists\n", + "my_list = [\"banana\", \"cherry\", \"apple\"]\n", + "new_list = sorted(my_list)\n", + "\n", + "# create list with repeated elements\n", + "list_with_zeros = [0] * 5\n", + "print(list_with_zeros)\n", + "\n", + "# concatenation\n", + "list_concat = list_with_zeros + my_list\n", + "print(list_concat)\n", + "\n", + "# convert string to list\n", + "string_to_list = list('Hello')\n", + "print(string_to_list)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Copy a list\n", + "Be careful when copying references." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['banana', 'cherry', 'apple', True]\n", + "['banana', 'cherry', 'apple', True]\n", + "['banana', 'cherry', 'apple', True]\n", + "['banana', 'cherry', 'apple']\n" + ] + } + ], + "source": [ + "list_org = [\"banana\", \"cherry\", \"apple\"]\n", + "\n", + "# this just copies the reference to the list, so be careful\n", + "list_copy = list_org\n", + "\n", + "# now modifying the copy also affects the original\n", + "list_copy.append(True)\n", + "print(list_copy)\n", + "print(list_org)\n", + "\n", + "# use copy(), or list(x) to actually copy the list\n", + "# slicing also works: list_copy = list_org[:]\n", + "list_org = [\"banana\", \"cherry\", \"apple\"]\n", + "\n", + "list_copy = list_org.copy()\n", + "# list_copy = list(list_org)\n", + "# list_copy = list_org[:]\n", + "\n", + "# now modifying the copy does not affect the original\n", + "list_copy.append(True)\n", + "print(list_copy)\n", + "print(list_org)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Iterating" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "banana\n", + "cherry\n", + "Morning\n", + "Everybody\n" + ] + } + ], + "source": [ + "# Iterating over a list by using a for in loop\n", + "for i in list_1:\n", + " print(i)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Check if an item exists" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "yes\n" + ] + } + ], + "source": [ + "if \"banana\" in list_1:\n", + " print(\"yes\")\n", + "else:\n", + " print(\"no\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Slicing\n", + "Access sub parts of the list wih the use of colon (:), just as with strings." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2, 3]\n", + "[3, 4, 5, 6, 7, 8, 9, 10]\n", + "[1, 2, 3]\n", + "[0, 4, 5, 6, 7, 8, 9, 10]\n", + "[0, 5, 7, 9]\n", + "[10, 9, 8, 7, 6, 5, 4, 0]\n", + "[10, 9, 8, 7, 6, 5, 4, 0]\n" + ] + } + ], + "source": [ + "# a[start:stop:step], default step is 1\n", + "a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", + "b = a[1:3] # Note that the last index is not included\n", + "print(b)\n", + "b = a[2:] # until the end\n", + "print(b)\n", + "b = a[:3] # from beginning\n", + "print(b)\n", + "a[0:3] = [0] # replace sub-parts, you need an iterable here\n", + "print(a)\n", + "b = a[::2] # start to end with every second item\n", + "print(b)\n", + "a = a[::-1] # reverse the list with a negative step:\n", + "print(a)\n", + "b = a[:] # copy a list with slicing\n", + "print(b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### List comprehension\n", + "A elegant and fast way to create a new list from an existing list.\n", + "\n", + "List comprehension consists of an expression followed by a for statement inside square brackets." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 4, 9, 16, 25, 36, 49, 64]\n" + ] + } + ], + "source": [ + "a = [1, 2, 3, 4, 5, 6, 7, 8]\n", + "b = [i * i for i in a] # squares each element\n", + "print(b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Nested lists\n", + "Lists can contain other lists (or other container types)." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[1, 2], [3, 4]]\n", + "[1, 2]\n" + ] + } + ], + "source": [ + "a = [[1, 2], [3, 4]]\n", + "print(a)\n", + "print(a[0])" + ] + } + ], + "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.7.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} From 0d3a107fdd908b0a41a41b80727e4e9ba44c1e25 Mon Sep 17 00:00:00 2001 From: Abhijit-Moholkar <89727322+Abhijit-Moholkar@users.noreply.github.com> Date: Fri, 5 Nov 2021 03:33:45 -0700 Subject: [PATCH 2/2] Addition of some more methods Included some usefull methods for better understanding --- 05-Strings.ipynb | 491 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 491 insertions(+) create mode 100644 05-Strings.ipynb diff --git a/05-Strings.ipynb b/05-Strings.ipynb new file mode 100644 index 0000000..da1f307 --- /dev/null +++ b/05-Strings.ipynb @@ -0,0 +1,491 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Strings\n", + "A string is a sequence of characters. String literals in Python are enclosed by either double or single quotes.\n", + "\n", + "`my_string = 'Hello'`\n", + "\n", + "Python strings are immutable which means they cannot be changed after they are created." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Creation" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "I' m a 'Geek'\n", + "Hello\n", + "World\n", + "Hello World!!! How are you?\n" + ] + } + ], + "source": [ + "# Creation of empty string\n", + "new_string = ''\n", + "print(new_string)\n", + "print(type(new_string))\n", + "\n", + "# use singe or double quotes\n", + "my_string = 'Hello'\n", + "my_string = \"Hello\"\n", + "my_string = \"I' m a 'Geek'\"\n", + "\n", + "# escaping backslash\n", + "my_string = 'I\\' m a \"Geek\"'\n", + "my_string = 'I\\' m a \\'Geek\\''\n", + "print(my_string)\n", + "\n", + "# triple quotes for multiline strings(DocString)\n", + "my_string = \"\"\"Hello\n", + "World\"\"\"\n", + "print(my_string)\n", + "\n", + "# backslash if you want to continue in the next line\n", + "my_string = \"Hello \\\n", + "World!!! \\\n", + "How \\\n", + "are \\\n", + "you?\"\n", + "print(my_string)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Access characters and substrings" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "H\n", + "el\n", + "Hello\n", + "World\n", + "HloWrd\n", + "el ol\n", + "dlroW olleH\n" + ] + } + ], + "source": [ + "my_string = \"Hello World\"\n", + "\n", + "# get character by referring to index\n", + "b = my_string[0]\n", + "print(b)\n", + "\n", + "# Substrings with slicing\n", + "b = my_string[1:3] # Note that the last index is not included\n", + "print(b)\n", + "b = my_string[:5] # from beginning\n", + "print(b)\n", + "b = my_string[6:] # until the end\n", + "print(b)\n", + "b = my_string[::2] # start to end with every second item\n", + "print(b)\n", + "b = my_string[1::2] # Retrieve characters at odd index\n", + "print(b)\n", + "b = my_string[::-1] # reverse the string with a negative step:\n", + "print(b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Concatenate two or more strings" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello Tom\n" + ] + } + ], + "source": [ + "# concat strings with +\n", + "greeting = \"Hello\"\n", + "name = \"Tom\"\n", + "sentence = greeting + ' ' + name\n", + "print(sentence)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Iterating" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "H\n", + "e\n", + "l\n", + "l\n", + "o\n" + ] + } + ], + "source": [ + "# Iterating over a string by using a for in loop\n", + "my_string = 'Hello'\n", + "for i in my_string:\n", + " print(i)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Check if a character or substring exists" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "No\n", + "yes\n" + ] + } + ], + "source": [ + "if \"m\" in \"Hello\":\n", + " print(\"yes\")\n", + "else:\n", + " print(\"No\")\n", + "if \"llo\" in \"Hello\":\n", + " print(\"yes\")\n", + "else:\n", + " print(\"No\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Useful methods" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "$ $$Hello# W@orld* 22\n", + "$ $$Hello# W@orld* 28\n", + "$ $$Hello# W@orld* 22\n", + " $$Hello# W@orld* \n", + "HelloWorld\n", + "28\n", + "$ $$HELLO# W@ORLD* \n", + "$ $$Hello# W@Orld* \n", + "$ $$hello# w@orld* \n", + "$ $$hello# w@orld* \n", + "True\n", + "False\n", + "True\n", + "False\n", + "4\n", + "5\n", + "2\n", + "5\n", + "1\n", + "Hello Universe\n", + "['how', 'are', 'you', 'doing']\n", + "['one', 'two', 'three']\n", + "How are you doing\n", + "one,two,three*******\n", + "*******one,two,three\n", + "***one,two,three****\n" + ] + } + ], + "source": [ + "my_string = \"$ $$Hello# W@orld* \"\n", + "\n", + "# Remove white spaces at both ends of string\n", + "print(my_string.strip(),len(my_string.strip()))\n", + "\n", + "# Remove white spaces at left ends of string\n", + "print(my_string.lstrip(),len(my_string.lstrip()))\n", + "\n", + "# Remove white spaces at Right ends of string\n", + "print(my_string.rstrip(),len(my_string.rstrip()))\n", + "\n", + "# Remove unwanted characters at both ends of string\n", + "print(my_string.strip('$#@*')) # It will remove first $ but not at the middle\n", + "\n", + "# Remove unwanted characters from string\n", + "print(''.join(filter(str.isalnum,my_string))) # It will remove all non-alpha-numeric characters\n", + "\n", + "# number of characters\n", + "print(len(my_string))\n", + "\n", + "# Change case of sting\n", + "print(my_string.upper()) # To convert string in upper case\n", + "print(my_string.title()) # To convert string in title case \n", + "print(my_string.lower()) # To convert string in lower case\n", + "print(my_string.casefold()) # To convert string in lower case including special notations of other languages\n", + "\n", + "# Check whether string starts with or ends with specific characters: It returns boolean output\n", + "print(\"hello\".startswith(\"he\")) # True\n", + "print(\"hello\".startswith(\"eh\")) # False\n", + "print(\"hello\".endswith(\"llo\")) # True\n", + "print(\"hello\".endswith(\"lol\")) # False\n", + "\n", + "# find first index of a given substring, -1 otherwise\n", + "print(\"Hello\".find(\"o\"))\n", + "\n", + "# find last index of a given substring, -1 otherwise\n", + "print(\"Heollo\".rfind(\"o\"))\n", + "\n", + "# Return first index of a given substring, ValueError otherwise\n", + "print(\"Heollo\".index(\"o\"))\n", + "\n", + "# Return last index of a given substring, ValueError otherwise\n", + "print(\"Heollo\".rindex(\"o\"))\n", + "\n", + "# count number of characters/substrings\n", + "print(\"Hello\".count(\"e\"))\n", + "\n", + "# replace a substring with another string (only if the substring is found)\n", + "# Note: The original string stays the same\n", + "message = \"Hello World\"\n", + "new_message = message.replace(\"World\", \"Universe\")\n", + "print(new_message)\n", + "\n", + "# split the string into a list\n", + "my_string = \"how are you doing\"\n", + "a = my_string.split() # default argument is \" \"\n", + "print(a)\n", + "my_string = \"one,two,three\"\n", + "a = my_string.split(\",\")\n", + "print(a)\n", + "\n", + "# join elements of a list into a string\n", + "my_list = ['How', 'are', 'you', 'doing']\n", + "a = ' '.join(my_list) # the given string is the separator, e.g. ' ' between each argument\n", + "print(a)\n", + "\n", + "# Change string allignment\n", + "print(my_string.ljust(20,'*')) # Left allignment\n", + "print(my_string.rjust(20,'*')) # right allignment\n", + "print(my_string.center(20,'*')) # center allignment" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Format\n", + "New style is with .format() and old style is with % operator." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello Bob and Tom\n", + "Hello Bob and Tom\n", + "Hello Tom and Bob\n", + "The integer value is 2\n", + "The float value is 2.123\n", + "The float value is 2.123400e+00\n", + "The binary value is 10\n", + "Hello Bob and Tom\n", + "The decimal value is 3\n", + "The float value is 3.141593\n", + "The float value is 3.14\n" + ] + } + ], + "source": [ + "# use braces as placeholders\n", + "a = \"Hello {0} and {1}\".format(\"Bob\", \"Tom\")\n", + "print(a)\n", + "\n", + "# the positions are optional for the default order\n", + "a = \"Hello {} and {}\".format(\"Bob\", \"Tom\")\n", + "print(a)\n", + "\n", + "# Its possible to change order\n", + "a = \"Hello {1} and {0}\".format(\"Bob\", \"Tom\")\n", + "print(a)\n", + "\n", + "a = \"The integer value is {}\".format(2)\n", + "print(a)\n", + "\n", + "# some special format rules for numbers\n", + "a = \"The float value is {0:.3f}\".format(2.1234)\n", + "print(a)\n", + "a = \"The float value is {0:e}\".format(2.1234)\n", + "print(a)\n", + "a = \"The binary value is {0:b}\".format(2)\n", + "print(a)\n", + "\n", + "# old style formatting by using % operator\n", + "print(\"Hello %s and %s\" % (\"Bob\", \"Tom\")) # must be a tuple for multiple arguments\n", + "val = 3.14159265359\n", + "print(\"The decimal value is %d\" % val)\n", + "print(\"The float value is %f\" % val)\n", + "print(\"The float value is %.2f\" % val)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### f-Strings\n", + "New since Python 3.6. Use the variables directly inside the braces." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, Eric. You are 25.\n", + "Pi is 3.142\n", + "The value is 120\n" + ] + } + ], + "source": [ + "name = \"Eric\"\n", + "age = 25\n", + "a = f\"Hello, {name}. You are {age}.\"\n", + "print(a)\n", + "pi = 3.14159\n", + "a = f\"Pi is {pi:.3f}\"\n", + "print(a)\n", + "# f-Strings are evaluated at runtime, which allows expressions\n", + "a = f\"The value is {2*60}\"\n", + "print(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### More on immutability and concatenation" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "concatenate string with + : 0.34796\n", + "concatenate string with join(): 0.01090\n" + ] + } + ], + "source": [ + "# since a string is immutable, adding strings with +, or += always \n", + "# creates a new string, and therefore is expensive for multiple operations\n", + "# --> join method is much faster\n", + "from timeit import default_timer as timer\n", + "my_list = [\"a\"] * 1000000\n", + "\n", + "# bad\n", + "start = timer()\n", + "a = \"\"\n", + "for i in my_list:\n", + " a += i\n", + "end = timer()\n", + "print(\"concatenate string with + : %.5f\" % (end - start))\n", + "\n", + "# good\n", + "start = timer()\n", + "a = \"\".join(my_list)\n", + "end = timer()\n", + "print(\"concatenate string with join(): %.5f\" % (end - start))" + ] + } + ], + "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.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +}