--- title: Introduction description: duration: 200 card_type: cue_card --- # **Strings 2 (2 hours)** [Class Recording](https://www.scaler.com/meetings/i/beginner-strings-2-13/archive) [Lecture Notes](https://scaler-production-new.s3.ap-southeast-1.amazonaws.com/attachments/attachments/000/015/558/original/Strings_2.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIDNNIRGHAQUQRWYA%2F20221205%2Fap-southeast-1%2Fs3%2Faws4_request&X-Amz-Date=20221205T044912Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=60169527e2359ff6276313309b10c3fa89ddd93838cb637c599959cddf38c7ea) [Old Script](https://colab.research.google.com/drive/12GS8NQuNbxDrMQoDd4IdLxWZ-GQWOXYz?usp=sharing) ## **Content** 1. Various String methods. 2. Concept of Mutability and Immutability ### Meanwhile when people are joining (5-7 mins) * Instructor's welcome. * Breaking ice with students. * Casual conversation to bond. --- title: Quiz-1 description: duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= message = "Hello World!" i = 0 while i < len(message): if i % 2 == 0: print(message[i], end = "") i += 1 ``` # Choices - [x] HloWrd - [ ] Hlo ol - [ ] eolWrd - [ ] el or --- title: String Methods description: duration: 2400 card_type: cue_card --- ## String Methods ### .split() method * The str.split() function converts a string into a list of characters based on a splitting criteria. Code: ```python= "4 5 6 7 8 9".split() ``` >Output: ``` ['4', '5', '6', '7', '8', '9'] ``` Code: ```python= "This_is_a_underscore_separated_string".split("_") ``` >Output: ``` ['This', 'is', 'a', 'underscore', 'separated', 'string'] ``` ### .join() method * Opposite of splitting is joining. * We can use str.join() to do so. Code: ```python= random = "This_is_a_underscore_separated_string".split("_") " ".join(random) ``` >Output: ``` 'This is a underscore separated string' ``` Code: ```python= "-".join(random) ``` >Output: ``` 'This-is-a-underscore-separated-string' ``` * While providing an iterable to .join() you need to make sure that the contents of that iterable only contain strings. Else it will throw an error. Code: ```python= # Error a = ["random", 102, 282, "string"] " ".join(a) ``` >Output: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-6c67814fded6> in <module> 1 a = ["random", 102, 282, "string"] ----> 2 " ".join(a) TypeError: sequence item 1: expected str instance, int found ``` ### str() function * We can use str() function to convert numbers to string. Code: ```python= str(45) ``` >Output: ``` '45' ``` ### .find() method * The .find() method can be used to find a substring inside a string that we can call it on. * This function returns the starting index of the first occourance of the substring that we are trying to find inside the string. Code: ```python= "this is a random string".find("is") ``` >Output: ``` 2 ``` * Returns -1 if the substring is not present. Code: ```python= "this is a random string".find("adadsaf") ``` >Output: ``` -1 ``` ### .replace() method * The method .replace() can be used to replace a substring from the original string with the input we provide. * This method takes in two arguments, first the substring from the original string and second the string we want to replace it with. * It replaces the string we provide and returns a new string. Code: ```python= random = "This is a random string that I have created" # The orginal string is not updated. random.replace("random", "SUPER RANDOM") ``` >Output: ``` 'This is a SUPER RANDOM string that I have created' ``` ### .count() method * The method .count() can be used to count the number of occourances of a substring we provide inside a particular string. Code: ```python= random = "This is a random string that I have created" random.count("a") ``` >Output: ``` 5 ``` Code: ```python= random = "This is a random string that I have created random random random" random.count("random") ``` >Output: ``` 4 ``` --- title: Question-1 description: duration: 480 card_type: cue_card --- * Take a string as input. * Convert the string to lowercase without using any inbuilt function. Code: ```python= def custom_lower(s): result = "" for i in s: if ord(i) >= 65 and ord(i) <= 90: order = ord(i) order = order + 32 result = result + chr(order) else: result = result + i return result custom_lower("This is A stRIng") ``` >Output: ``` 'this is a string' ``` --- title: Quiz-2 description: duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= message = "Hello World!" print(message.lower()) ``` # Choices - [ ] HELLO WORLD! - [x] hello world! - [ ] hELLO wORLD! - [ ] Hello World! --- title: Quiz-3 description: duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= message = "Hello World!" print(message.replace("o", "e")) ``` # Choices - [ ] Helle Welle - [ ] Helle Welle! - [x] Helle Werld! - [ ] Hllo Wrld! --- title: Some more methods description: duration: 1800 card_type: cue_card --- ## Some more methods - ### .isdigit() * .isdigit() returns True a character inside a string is a digit. * This method works only for integers. Code: ```python= "6".isdigit() ``` >Output: ``` True ``` Code: ```python= "a".isdigit() ``` >Output: ``` False ``` Code: ```python: "aasda231321".isdigit() ``` >Output: ``` False ``` Code: ```python= "124143222".isdigit() ``` >Output: ``` True ``` ### .isalpha() * isalpha() returns True if a certain string only contains alphabets Code: ```python= "aasda231321".isalpha() ``` >Output: ``` False ``` Code: ```python= "a".isalpha() ``` >Output: ``` True ``` Code: ```python= "abc".isalpha() ``` >Output: ``` True ``` ### .isupper() and .islower() Code: ```python= "A".isupper() ``` Output: ``` True ``` Code: ```python= "a".isupper() ``` Output: ``` False ``` Code: ```python= "a".islower() ``` Output: ``` True ``` Code: ```python= "A".islower() ``` Output: ``` False ``` ### .isspace() * Returns True if there is a space in the string. Code: ```python= "abc".isspace() ``` >Output: ``` False ``` Code: ```python= " ".isspace() ``` >Output: ``` True ``` --- title: Question-2 description: duration: 400 card_type: cue_card --- * Take a string as input. * Replace all the space with underscore. Code: ```python= string = "this is a random string" # 1 def change_to_underscore(s): result = "" for i in s: if i.isspace(): result = result + "_" else: result = result + i return result change_to_underscore(string) ``` >Output: ``` 'this_is_a_random_string' ``` Code: ```python= # 2 string.replace(" ", "_") ``` >Output: ``` this_is_a_random_string ``` --- title: Quiz-4 description: duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= message = "Not Hello World!" print(message.startswith("Hello")) ``` # Choices - [ ] True - [x] False - [ ] None - [ ] Error --- title: Quiz-5 description: duration: 60 card_type: quiz_card --- # Question What will be the output of the following code? ```python= message = "Hello World!" print(message.find("o")) ``` # Choices - [ ] 8 - [ ] 7 - [x] 4 - [ ] -1 --- title: Glossary of string methods description: duration: 90 card_type: cue_card --- ### Glossary of string methods - <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/039/775/original/glossary_of_str_methods.png?1689241237" width=600 height=350> --- title: Mutability and Immutability description: duration: 900 card_type: cue_card --- ### Mutability and Immutability Mutable: whose value can change. Immutable: whose value can't change. <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/039/776/original/mutable_and_immutable_explaination.png?1689241538" width=600 height=150> <img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/039/777/original/mutable_and_immutable_explaination_2.png?1689241570" width=600 height=350> Code: ```python= a = 3 a ``` >Output: ``` 3 ``` Code: ```python= a = 4 a ``` >Output: ``` 4 ``` It seems that integers are mutable but NO. originally in python we are just changing the memory reference of a to point to 4 instead of changing its value to 4. Only 3 data types in python are mutable * list * sets * dictionaries Other data types such as strings and tuples(you are going to learn in upcoming lectures) are immutable. > id() function in python gives the memory address of the variable where it is stored Code: ```python= id(a) ``` >Output: ``` 140424322138448 ``` Code: ```python= a = 6 id(a) # it can be seen that memory address is change hence now a is pointing to somewhere else in memory ``` >Output: ``` 140424322138512 ``` Code: ```python= my_list =["Python", "C++", "Java"] id(my_list) ``` >Output: ``` 140423632449408 ``` Code: ```python= my_list.append("HTML") my_list[0] = "Python 3.5" print(my_list) print(id(my_list)) ``` >Output: ``` ['Python 3.5', 'C++', 'Java', 'HTML', 'HTML'] 140423632449408 ``` As lists are mutable, we can see that the same list created in the first cell is modified and the values are changed in the same memory location. Code: ```python= my_string = "Scaled" my_string[5] = "r" # Trying to change the character in the last index print(my_string) ``` >Output: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-5b191cb176fc> in <cell line: 2>() 1 my_string = "Scaled" ----> 2 my_string[5] = "r" # Trying to change the character in the last index 3 print(my_string) TypeError: 'str' object does not support item assignment ``` * We receive an error as strings are immutable and we cannot change the value in place. * We can instead assign a new value to the same variable, which leads to the creation of a different memory space Code: ```python= print(id(my_string)) ``` >Output: ``` 140423625872112 ``` Code: ```python= my_string = "Scaler" print(id(my_string)) ``` >Output: ``` 140423066082608 ```