{ "cells": [ { "cell_type": "markdown", "id": "b0cf17d5", "metadata": {}, "source": [ "--- \n", " \n", "\n", "

Department of Data Science

\n", "

Course: Tools and Techniques for Data Science

\n", "\n", "---\n", "

Instructor: Muhammad Arif Butt, Ph.D.

" ] }, { "cell_type": "markdown", "id": "351c3150", "metadata": {}, "source": [ "

Lecture 2.4

" ] }, { "cell_type": "markdown", "id": "b9271b7c", "metadata": {}, "source": [ "\"Open" ] }, { "cell_type": "markdown", "id": "f258f97c", "metadata": {}, "source": [ "## _Python-Strings.ipynb_\n", "#### [Learn more about Python Strings](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str)" ] }, { "cell_type": "markdown", "id": "0a41a8be", "metadata": {}, "source": [ " \n", "\n", "## Learning agenda of this notebook\n", "A String is an object type in Python, that is used to record textual information. String data type is actually a sub-type of a broader classification of object type called sequence. A sequence is an object that contains components placed one after the other, where each object is given a numeric index, which identifies that component and its position within the whole sequence. As Python is a zero indexed based language, the first object of any sequence is always indexed zero. A string is defined using opening and closing delimiters. These delimiters are single or double quotes\n", "\n", "\n", "\n", "1. Defining strings in Python\n", "2. Accessing characters of a string in Python\n", "3. Strings are immutable\n", "4. Slicing strings\n", "5. String concatenation\n", "6. Creating large strings\n", "\n", "7. String Methods: `lower()`, `upper()`, `strip()`, `startswith()`, `split()`, `join()`, `find()`, `replace()`, `format()`\n", "8. String Membership test" ] }, { "cell_type": "markdown", "id": "9f811f89", "metadata": {}, "source": [ "## 1. Defining Strings in Python\n", "- A string is a collection of character(s) closed within single or double quotation marks. (There is no `char` data type in Python as in C/C++)\n", "- A string can also contain a single character or be entirely empty.\n", "- To make a single quote part of a string, define the string using double quotes and vice versa. You can also make use of escape sequence" ] }, { "cell_type": "code", "execution_count": 1, "id": "e360d31b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\n", "World\n", "\n", "A\n" ] } ], "source": [ "string1 = 'Hello'\n", "print(string1)\n", "\n", "string2 = \"World\"\n", "print(string2)\n", "\n", "string3 = \"\"\n", "print(string3)\n", "\n", "string4 = \"A\"\n", "print(string4)" ] }, { "cell_type": "code", "execution_count": 2, "id": "30ceb2f2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, This is\n", " multi-line string\n", "Hello, This is\n", " multi-line string\n" ] } ], "source": [ "# triple quotes string can extend multiple lines\n", "\n", "string5 = \"\"\"Hello, This is\n", " multi-line string\"\"\"\n", "print(string5)\n", "\n", "string5 = '''Hello, This is\n", " multi-line string'''\n", "print(string5)" ] }, { "cell_type": "code", "execution_count": null, "id": "2539e811", "metadata": {}, "outputs": [], "source": [ "# Be careful with quotes!\n", "'I'm using single quotes, but will create an error'" ] }, { "cell_type": "markdown", "id": "eb95d10e", "metadata": {}, "source": [ "The reason for the error above is because the single quote in I'm stopped the string. You can use combinations of double and single quotes to get the complete statement." ] }, { "cell_type": "code", "execution_count": 3, "id": "6f79c557", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"Now I'm ready to use the single quotes inside a string!\"" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"Now I'm ready to use the single quotes inside a string!\"" ] }, { "cell_type": "markdown", "id": "3a978533", "metadata": {}, "source": [ "Escape characters. If there is some where situation where you need a bunch of quotes, you can use escape character \\' \\'.\n", "Just make sure you close the end of the string without the escape character ." ] }, { "cell_type": "code", "execution_count": null, "id": "c559d6e2", "metadata": {}, "outputs": [], "source": [ "'Now I\\'m ready to use the single quotes inside a string!'" ] }, { "cell_type": "markdown", "id": "d3e111e1", "metadata": {}, "source": [ "## 2. Accessing Characters of a String in Python\n", "- Since string is of type sequence, and any component within a sequence can be accessed by entrying an index within square brackets. So naturally this work for strings as well\n", "- Similarly, if we want to find out the index of a specific item/character, we can use the `str.index()` method" ] }, { "cell_type": "code", "execution_count": 4, "id": "b99f10c5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "str = Python Programming is fun\n", "str[0] = P\n", "str[-1] = n\n", "str[-2] = u\n" ] } ], "source": [ "str = 'Python Programming is fun'\n", "print('str = ', str)\n", "\n", "#access first index\n", "print('str[0] = ', str[0])\n", "\n", "# Negative indices start from the opposite end of the string. Hence, -1 index corresponds to the last character\n", "print('str[-1] = ', str[-1])\n", "\n", "#access second last index\n", "print('str[-2] = ', str[-2])\n", "\n", "#print(str[17]) #access an index out of the range, will get error\n", "\n", "#print(str[1.5]) #use numbers other than an integer as index will flag an error" ] }, { "cell_type": "code", "execution_count": null, "id": "30a13986", "metadata": {}, "outputs": [], "source": [ "# To find out the index of a specific character\n", "str = \"Python Programming is fun\"\n", "str.index('th')" ] }, { "cell_type": "code", "execution_count": null, "id": "6d910aec", "metadata": {}, "outputs": [], "source": [ "dir()" ] }, { "cell_type": "markdown", "id": "5cbf1435", "metadata": {}, "source": [ "## 3. Strings are Immutable" ] }, { "cell_type": "code", "execution_count": 4, "id": "327aea83", "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'string' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_27309/2810742144.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mhelp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstring\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'string' is not defined" ] } ], "source": [ "help(string)" ] }, { "cell_type": "code", "execution_count": null, "id": "d0771648", "metadata": {}, "outputs": [], "source": [ "#strings are immutable, means string object does not support item assignment\n", "str1 = 'ArifButt'\n", "\n", "#str1[5] = 'c'\n", "\n", "print(id(str1))\n", "\n", "#assigning a new value is valid\n", "str1 = 'python'\n", "\n", "print(id(str1))" ] }, { "cell_type": "markdown", "id": "4c49337a", "metadata": {}, "source": [ "The object `ArifButt` is now orphan, since there is no variable referring to it now and will be collected by Python garbage collector." ] }, { "cell_type": "markdown", "id": "e8c7221e", "metadata": {}, "source": [ "## 4. Slicing Strings\n", "- Slicing is the process of obtaining a portion (substring) of a string by using its indices.\n", "- Given a string, we can use the following syntax to slice it and obtain a substring:\n", "```\n", "string[start:end]\n", "```\n", "\n", "- **start** is the index from where we want the substring to start. If start is not provided, slicing starts from the beginning.\n", "- **end** is the index where we want our substring to end (not inclusive in the substring). If end is not provided, slicing goes till the end of the string (includes the last character of the string)." ] }, { "cell_type": "code", "execution_count": 22, "id": "a45eb434", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Data\n", "Data\n", "Tools\n", "Techniques\n", "Techniques\n", "\n" ] } ], "source": [ "str1 = 'DataScienceToolsAndTechniques'\n", "\n", "print(str1[0:4]) # From the start till before the 4th index\n", "print(str1[:4]) # From the start till before the 4th index\n", "print(str1[11:16])\n", "print(str1[19:]) # From the 19th index till the end\n", "print(str1[19:len(str)]) # From the 19th index till the end\n", "#if start is greater than end, it will return empty string\n", "print(str1[5:2])" ] }, { "cell_type": "markdown", "id": "29823e0e", "metadata": {}, "source": [ "### a. Slicing with a Step \n", "- In the above example, we’ve used slicing to obtain a contiguous piece of a string, i.e., all the characters from the starting index to before the ending index are retrieved.\n", "- However, we can define a step through which we can skip characters in the string. The default step is 1, so we iterate through the string one character at a time.\n", "- The step is defined after the end index:\n", "```\n", "string[start:end:step]\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "340a1dd5", "metadata": {}, "outputs": [], "source": [ "str1 = 'DataScienceToolsAndTechniques'\n", "print(str1[::]) # A default step of 1\n", "print(str1[::1]) # A step of 1\n", "print(str1[::2]) # A step of 2" ] }, { "cell_type": "markdown", "id": "df2b33e0", "metadata": {}, "source": [ "### b. Reverse Slicing\n", "- Strings can also be sliced to return a reversed substring. \n", "- For reverse slicing we need to give a negative step\n", "- For reverse slicing the `start` index must be greater than the `end` index, otherwise an empty string will be returned" ] }, { "cell_type": "code", "execution_count": 23, "id": "9f1d3ebb", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9876543210\n", "5432\n", "\n", "97531\n" ] } ], "source": [ "str1 = '0123456789'\n", "print(str1[::-1]) \n", "print(str1[5:1:-1]) \n", "print(str1[2:10:-1])\n", "print(str1[::-2]) " ] }, { "cell_type": "markdown", "id": "2603ff7c", "metadata": {}, "source": [ "## 5. String Concatenation\n", "- Two strings can be joined or concatenated using the `+` operator" ] }, { "cell_type": "code", "execution_count": null, "id": "44dc0a9d", "metadata": {}, "outputs": [], "source": [ "str1 = 'Hello'\n", "str2 =' World!'\n", "str3 = str1 + str2\n", "print('str1 + str2 = ', str3)\n", "\n", "\n", "print(\"Y\" + str3[1:])" ] }, { "cell_type": "markdown", "id": "f4bdee54", "metadata": {}, "source": [ "## 6. Creating Large strings\n", "- A string can be replicated/repeated using the `*` operator" ] }, { "cell_type": "code", "execution_count": 6, "id": "5fcc181e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "str1 * 3 = HelloHelloHelloHelloHello\n", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" ] } ], "source": [ "str1 = 'Hello'\n", "print('str1 * 5 =', str1 * 5)\n", "\n", "buffer = 'A' * 100\n", "print(buffer)" ] }, { "cell_type": "code", "execution_count": null, "id": "72483328", "metadata": {}, "outputs": [], "source": [ "\"Arif\"*100" ] }, { "cell_type": "markdown", "id": "be6f1cc8", "metadata": {}, "source": [ "## 7. String Methods\n", "- Objects in Python usually have built-in **methods**. These methods are functions defined in the class that can perform actions on the object of that class. \n", "- To keep it simple, methods are actions that are performed on object of a class, while functions are actions that belong to no 'data thing' (object). They just exist in the program.\n", "- Methods will perform specific actions on the object and can also take arguments. We call methods with a period and then the method name. Basically, we say `\"Hey object, do this to these arguments\"`. The syntax to call methods is:\n", "```\n", "object.method(arg1, arg2, ...)\n", "```\n", "- Where parameters are extra arguments we can pass to the method.\n", "- Remember, most of the String methods do not modify the string object on which they are called, rather return a new string object that has been altered as per the requested opertaion. \n", "- Let me re-emphasize, that all string methods return new values and DO NOT change the existing string. \n", "- [Click me to learn more about string methods](https://www.w3schools.com/python/python_ref_string.asp)" ] }, { "cell_type": "markdown", "id": "a37b6a03", "metadata": {}, "source": [ "### a. The `len()`, `str.lower()`, `str.upper()` and `str.capitalize()` methods\n", "- The `len()` is a built-in function that returns the number of items of a container data type passed as argument. We can check the length of any data types that are collections with built-in `len()` function.\n", "It is considered a built-in function.\n", "- The `str.lower()` method return a copy of the string converted to lowercase.\n", "- The `str.upper()` method return a copy of the string converted to uppercase.\n", "- The `str.capitalize()` method return a capitalized version of the string." ] }, { "cell_type": "code", "execution_count": null, "id": "57d585c3", "metadata": {}, "outputs": [], "source": [ "help(len)" ] }, { "cell_type": "code", "execution_count": 24, "id": "78745769", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str1= \"Hello World\"\n", "mylist = [1,2,3,4,5]\n", "len(str1)\n", "len(mylist)" ] }, { "cell_type": "markdown", "id": "6bf7d0e1", "metadata": {}, "source": [ "- To know what all methods the object of string class support. Just type the name of the object, place a dot and then press to view the list of its attributes and methods it support. \n", "`str.`\n", "- Similarly to get help about a method, after the method name press , to get information about what the method do, what parameters it take, its return value\n", "`str.lower`" ] }, { "cell_type": "code", "execution_count": null, "id": "f310670a", "metadata": {}, "outputs": [], "source": [ "str1=\"DS\"\n", "str." ] }, { "cell_type": "code", "execution_count": 25, "id": "3f201280", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Orignial string = LearNing is Fun with Arif\n", "len(str1) = 25\n", "str1.lower() = learning is fun with arif\n", "str1.upper() = LEARNING IS FUN WITH ARIF\n", "str1.capitalize() = Welcome to learning data science with arif\n", "Orignial string = LearNing is Fun with Arif\n" ] } ], "source": [ "str1 = 'LearNing is Fun with Arif'\n", "print('Orignial string = ', str1)\n", "\n", "rv = len(str1)\n", "print('len(str1) = ', rv)\n", "\n", "rv = str1.lower()\n", "print('str1.lower() = ', rv)\n", " \n", "print('str1.upper() = ', str1.upper())\n", "\n", "rv = str.capitalize()\n", "print('str1.capitalize() = ', rv)\n", "print('Orignial string = ', str1)\n" ] }, { "cell_type": "markdown", "id": "aee78026", "metadata": {}, "source": [ "### b. The `str.strip()` method\n", "- The `str.strip()` method removes whitespace characters from the beginning and end of a string.\n", "- The `str.lstrip()` method removes whitespace characters from the beginning of a string.\n", "- The `str.rstrip()` method removes whitespace characters from the end of a string.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "06a6775d", "metadata": {}, "outputs": [], "source": [ "str1=\"DS\"\n", "help(str1.strip)" ] }, { "cell_type": "code", "execution_count": 26, "id": "2ec66201", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " hello world, this is Arif Butt \n", "hello world, this is Arif Butt\n" ] } ], "source": [ "buffer =\" hello world, this is Arif Butt \"\n", "rv = buffer.strip()\n", "print(buffer)\n", "print(rv)" ] }, { "cell_type": "code", "execution_count": 27, "id": "6c478fb4", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello world, this is Arif Butt '" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "buffer\n", "buffer.lstrip()" ] }, { "cell_type": "code", "execution_count": 28, "id": "70d85498", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' hello world, this is Arif Butt'" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "buffer\n", "buffer.rstrip()" ] }, { "cell_type": "markdown", "id": "8181b676", "metadata": {}, "source": [ "### c. The `str.startswith()` method\n", "The `str.startswith()` method return True if str starts with the specified prefix, False otherwise.\n", "```\n", "str.startswith(prefix[, start[, end]])\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "8c25d5f1", "metadata": {}, "outputs": [], "source": [ "str1=\"DS\"\n", "help(str1.startswith)" ] }, { "cell_type": "code", "execution_count": 29, "id": "cafc44b9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "True\n", "False\n", "True\n" ] } ], "source": [ "str1 = \"Learning is fun with Arif Butt\"\n", "\n", "rv = str1.startswith('Learning')\n", "print(rv)\n", "\n", "rv = str1.startswith('Arif')\n", "print(rv)\n", "\n", "\n", "rv = str1.startswith('Arif', 21)\n", "print(rv)\n", "\n", "# case sensitive\n", "rv = str1.startswith('arif', 21)\n", "print(rv)\n", "\n", "rv = str1.startswith('arn', 2, 10) # character at ending index is not included\n", "print(rv)\n" ] }, { "cell_type": "markdown", "id": "85f7b8a7", "metadata": {}, "source": [ "### d. The `str.split()` and `str.join()` method\n", "- The `str.split()` method splits a string into a list of strings at every occurrence of space character by default. You may pass a parameter `sep='i'` to split method to split at that specific character instead.\n", "- The `sep.join(list)` method is passed a list/iterable as parameter and is called on a separater character. It joins the strings inside the list to a single string and returns" ] }, { "cell_type": "code", "execution_count": null, "id": "7acfe4a2", "metadata": {}, "outputs": [], "source": [ "str1=\"DS\"\n", "help(str1.split)" ] }, { "cell_type": "code", "execution_count": 7, "id": "ec111ec7", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Learning', 'is', 'fun', 'with', 'Arif', 'Butt']\n", "\n" ] } ], "source": [ "str1 = 'Learning is fun with Arif Butt'\n", "rv = str1.split()\n", "print(rv)\n", "print(type(rv))" ] }, { "cell_type": "code", "execution_count": 8, "id": "8a72e43c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Learn', 'ng ', 's fun w', 'th Ar', 'f Butt']\n", "\n" ] } ], "source": [ "str1 = 'Learning is fun with Arif Butt'\n", "rv = str1.split(sep='i')\n", "print(rv)\n", "print(type(rv))" ] }, { "cell_type": "code", "execution_count": 30, "id": "35be205d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function join:\n", "\n", "join(iterable, /) method of builtins.str instance\n", " Concatenate any number of strings.\n", " \n", " The string whose method is called is inserted in between each given string.\n", " The result is returned as a new string.\n", " \n", " Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'\n", "\n" ] } ], "source": [ "str1=\"DS\"\n", "help(str1.join)" ] }, { "cell_type": "code", "execution_count": 31, "id": "84b556b6", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['L', 'e', 'a', 'r', 'n', 'i', 'n', 'g']" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mystr = \"L e a r n i n g\"\n", "mystr.split(' ')" ] }, { "cell_type": "code", "execution_count": 9, "id": "834eca1c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Learning', 'is', 'fun', 'with', 'Arif'] \n", "Learning is fun with Arif \n" ] } ], "source": [ "# The join() method takes all items in an iterable and joins them into one string.\n", "mylist = ['Learning', 'is', 'fun', 'with', 'Arif']\n", "\n", "#Note the separator is space character\n", "mystr = ' '.join(mylist)\n", "\n", "print(mylist, type(mylist))\n", "print(mystr, type(mystr))" ] }, { "cell_type": "code", "execution_count": 10, "id": "2fc9dece", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Arif', 'Rauf', 'Maaz', 'Hadeed', 'Mujahid', 'Mohid'] \n", "Arif#Rauf#Maaz#Hadeed#Mujahid#Mohid \n" ] } ], "source": [ "# You can call join() method on a separator or your choice\n", "mylist = ['Arif', 'Rauf', 'Maaz', 'Hadeed', 'Mujahid', 'Mohid']\n", "\n", "#Note the separator is hash character\n", "mystr = '#'.join(mylist)\n", "\n", "print(mylist, type(mylist))\n", "print(mystr, type(mystr))" ] }, { "cell_type": "markdown", "id": "3f759ac2", "metadata": {}, "source": [ "### e. The `str.find()` method\n", "- The `str.find()` method is used to find a substring from within a string, which returns the first index at which a substring occurs in a string. If no instance of the substring is found, the method returns -1.\n", "```\n", "str.find(substring, start, end)\n", "```\n", "where \n", " - `substring` is what we are searching for,\n", " - `start` is the index from where we want to start searching (default value is 0)\n", " - `end` is the index where we want to stop our search (default value is len(str) -1)" ] }, { "cell_type": "code", "execution_count": 32, "id": "58ce5dc1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "16\n", "4\n", "15\n", "-1\n", "4\n" ] } ], "source": [ "str1 = 'DataScienceToolsAndTechniques'\n", "print(str1.find('Data'))\n", "print(str1.find('And'))\n", "\n", "\n", "print(str1.find('S',2)) # second argument starts searching from that index\n", "print(str1.find('s',2)) # case sensitive\n", "\n", "print(str1.find('S',0, 4)) # third argument stops searching uptill that index\n", "print(str1.find('S',0, 5)) " ] }, { "cell_type": "markdown", "id": "c11e762b", "metadata": {}, "source": [ "### f. Use `str.replace()` method to find a substring\n", "- The `str.replace()` method returns a string after replacing all occurrences of `substring_to_be_replaced` with `new_string`.\n", "```\n", "str.replace(substring_to_be_replaced, new_string, count = -1)\n", "```\n", "- Note that `replace` returns a new string, and the original string is not modified." ] }, { "cell_type": "code", "execution_count": null, "id": "7c8e62c9", "metadata": {}, "outputs": [], "source": [ "str1=\"DS\"\n", "help(str1.replace)" ] }, { "cell_type": "code", "execution_count": null, "id": "7f2f698e", "metadata": {}, "outputs": [], "source": [ "print(\"hello\".replace(\"e\",\"a\"))" ] }, { "cell_type": "code", "execution_count": 33, "id": "93b57ec8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Welcome to Learning Data Science with Arif\n", "Welcome to Learning Life with Arif\n" ] } ], "source": [ "str1 = 'Welcome to Learning Data Science with Arif'\n", "newstring = str1.replace('Data Science', 'Life')\n", "print(str1)\n", "print(newstring)" ] }, { "cell_type": "markdown", "id": "cb193a5b", "metadata": {}, "source": [ "### g. The `str.format()` method\n", "- The `str.format()` method combines values of other data types, e.g., integers, floats, booleans, lists, etc. with strings. \n", "- You can use `str.format()` to construct output messages for display in the Python built-in `print()` function.\n", "- You put placeholders `{}` within the format string of `print()` function, and the arguments to the `str.format()` method are the variable names\n", "- The values of the variables are replaced with the arguments provided to the `str.format()` method." ] }, { "cell_type": "code", "execution_count": null, "id": "683c6aeb", "metadata": {}, "outputs": [], "source": [ "#Example 1:\n", "age = 51; name=\"Arif Butt\"\n", "\n", "print(\"Mr. {}, you are {} years old.\" .format(name, age))" ] }, { "cell_type": "code", "execution_count": null, "id": "b57ff578", "metadata": {}, "outputs": [], "source": [ "#Example 2:\n", "name=\"Hadeed Butt\"\n", "cost = 100\n", "discount = .2\n", "bill = cost - cost * discount\n", "\n", "print(\"Mr. {2}, your total cost is {1}, percentage discount is {3}, and bill is {0}\" \n", " . format(bill, cost, name, discount))\n" ] }, { "cell_type": "markdown", "id": "8befae56", "metadata": {}, "source": [ "### Comparing two strings using `is` operator and `==` operator" ] }, { "cell_type": "code", "execution_count": null, "id": "8ac11b1b", "metadata": {}, "outputs": [], "source": [ "# Let us check out the IDs of the following two variables. Like numbers type of variable, \n", "# they are same as both a and b refers to the same memory location containing string 'hello'\n", "a = 'hello'\n", "b = 'hello'\n", "id(a), id(b)" ] }, { "cell_type": "code", "execution_count": null, "id": "d787d540", "metadata": {}, "outputs": [], "source": [ "# in case of strings, both a and b refers to the same memory location containing string 'hello'\n", "a = 'hello'\n", "b = 'hello'\n", "\n", "# The `is` operator checks the memory address of two strings \n", "print (a is b) \n", "# The `==` operator checks the contents of two strings\n", "print (a == b) \n", "\n", "\n", "print(a is not b)\n", "print (a != b)" ] }, { "cell_type": "code", "execution_count": null, "id": "d4e79e67", "metadata": {}, "outputs": [], "source": [ "# both x and y refers to two different memory locations containing string 'hello'\n", "x = 'hello'\n", "y = 'bye'\n", "\n", "# The `is` operator checks the memory address of two strings \n", "print (x is y) \n", "# The `==` operator checks the contents of two strings\n", "print (x == y) \n", "\n", "\n", "print(x is not y)\n", "print (x != y)" ] }, { "cell_type": "markdown", "id": "db4dd60b", "metadata": {}, "source": [ "### String Membership test using `in` operator" ] }, { "cell_type": "code", "execution_count": null, "id": "ad151253", "metadata": {}, "outputs": [], "source": [ "'a' in 'DataScience'" ] }, { "cell_type": "code", "execution_count": null, "id": "7dacbbf5", "metadata": {}, "outputs": [], "source": [ "'th' not in 'python'" ] }, { "cell_type": "markdown", "id": "0a975043", "metadata": {}, "source": [ "## Check your Concepts\n", "\n", "Try answering the following questions to test your understanding of the topics covered in this notebook:\n", "\n", "1. What are the container types available in Python?\n", "2. What kind of data does the String data type represent?\n", "3. What are the different ways of creating strings in Python?\n", "4. What is the difference between strings created using single quotes, i.e. `'` and `'` vs. those created using double quotes, i.e. `\"` and `\"`?\n", "5. How do you create multi-line strings in Python?\n", "6. What is the newline character, `\\n`?\n", "7. What are escaped characters? How are they useful?\n", "8. How do you check the length of a string?\n", "9. How do you convert a string into a list of characters?\n", "10. How do you access a specific character from a string?\n", "11. How do you access a range of characters from a string?\n", "12. How do you check if a specific character occurs in a string?\n", "13. How do you check if a smaller string occurs within a bigger string?\n", "14. How do you join two or more strings?\n", "15. What are \"methods\" in Python? How are they different from functions?\n", "16. What do the `.count`, `.isalnum` and `.isalpha` methods on strings do?\n", "17. How do you replace a specific part of a string with something else?\n", "18. How do you split the string \"Sun,Mon,Tue,Wed,Thu,Fri,Sat\" into a list of days?\n", "19. How do you remove whitespace from the beginning and end of a string?\n", "20. What is the string `.format` method used for? Can you give an example?\n", "21. What are the benefits of using the `.format` method instead of string concatenation?\n", "22. How do you convert a value of another type to a string?\n", "23. How do you check if two strings have the same value?\n", "24. Where can you find the list of all the methods supported by strings?" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }