# Session 3: Python 201 ###### tags: `CS Projects Class` --- ![](https://i.imgur.com/95LQmuG.png) --- ## String A string is simply a series of characters. Anything inside quotes is considered a string in Python, and you can use single or double quotes around your strings like this: --- ``` "This is a string" 'This is also a string' ``` --- --- #### This flexibility allows you to use quotes and apostrophes within your strings: --- ``` 'I told my friend, "Python is my favorite language!"' "The language 'Python' is named after Monty Python, not the snake." "One of Python's strengths is its diverse and supportive community." ``` --- --- There are many methods to work with strings. You can explore these methods at home: 1. title() 2. upper() 3. lower() --- ### Combining or Concatenating strings - Python uses the plus symbol (+) to combine strings. --- ``` >>>first_name = "Thinh" >>>last_name = "Tran" >>>full_name = first_name + ' ' + last_name >>>print(full_name) ``` --- - This method of combining strings is called ***concatenation***. --- ### Adding Whitespace to Strings with Tabs or Newlines In programming, whitespace refers to any nonprinting character, such as spaces, tabs, and end-of-line symbols. You can use whitespace to organize your output so it’s easier for users to read. --- To add a tab to your text, use the character combination \t as shown: --- ``` >>>print("Python") Python >>>print("\tPython") Python ``` --- --- To add a newline in a string, use the character combination \n: --- ``` >>>print("Languages:\nPython\nC\nJavaScript") Languages: Python C JavaScript ``` --- --- You can also combine tabs and newlines in a single string. --- ``` >>>print("Languages:\n\tPython\n\tC\n\tJavaScript") Languages: Python C JavaScript ``` --- --- ### Stripping Whitespace - Right strip: --- ``` >>> favorite_language = 'python ' >>> favorite_language 'python ' >>> favorite_language.rstrip() 'python' >>> favorite_language 'python ' ``` --- --- --- ``` >>> favorite_language = 'python ' >>> favorite_language = favorite_language.rstrip() >>> favorite_language 'python' ``` --- --- - Left strip & Strip: --- ``` >>> favorite_language = ' python ' >>> favorite_language.rstrip() ' python' >>> favorite_language.lstrip() 'python ' >>> favorite_language.strip() 'python' ``` --- --- The ***isnumeric*** method can check if a string is composed of only numbers. If the string contains only numbers, this method will return ***True***. We can use this to check if a string contains numbers before passing the string to the *int()* function to convert it to an integer, avoiding an error. --- ``` >>>n = "1234" >>>n.isnumeric() True ``` --- --- ### join & split method - This method is called on a string that will be used to join a list of strings. The method takes a list of strings to be joined as a parameter, and returns a new string composed of each of the strings from our list joined using the initial string. - For example, ***" ".join(["This","is","a","sentence"])*** would return the string ***"This is a sentence"***. --- - The inverse of the join method is the split method. This allows us to split a string into a list of strings. By default, it splits by any whitespace characters. You can also split by any other characters by passing a parameter. - For example, ***"This is a sentence".split()*** would return the list ***["This","is","a","sentence"]***. --- ### String indexing and slicing --- #### Locate substring --- ``` >>>animals = "tigers and lions" >>>animals.index("a") >>>animals.index("i") >>>animals.index("tigers") >>>animals.index("and") ``` --- --- If we try to locate a substring that doesn't exist in the string, we’ll receive a ***ValueError*** explaining that the substring was not found. --- #### What if we want to locate substring and character at index X? --- --- ``` >>>animals[0] >>>animals[0:5] ``` --- It is the same as working with a *list*, which we will learn later in this class. --- ![](https://i.imgur.com/o3IcUDk.png) --- ### Formatting - not just strings - Let's see some examples: --- ``` >>>name = "Thinh" >>>number = len(name) * 3 >>>print("Hello {}, your lucky number is {}.".format(name, number)) Hello Thinh, your lucky number is 15. ``` --- - ***{}*** is a variable placeholder to show where the variables should be written. Then, we pass the variables to the *format method*. - See how it does not matter that name is a *string* and number is an *integer*:question: --- One of the things we can put inside the curly brackets is the name of the variable we want in that position to make the whole string more ***readable***. --- ``` print("Your lucky number is {number}, {name}.".format(name=name, number=len(name)*3)) ``` And that is just the tip of the iceberg of what we can do with the format method. --- ### Let's dive deeper into this formatting method --- ``` >>>price = 7.5 >>>with_tax = price * 1.09 >>>print(price, with_tax) 7.5 8.175 >>>print("Base price: ${:.2f}. With tax: ${:.2f}".format(price, with_tax)) Base price: $7.50. With tax: $8.18 ``` --- ![](https://i.imgur.com/fLqzb6n.png) These expression starts with a colon to separate it from the field name that we saw before. After the colon, we write ***.2f***. This means we're going to format a float number and that there should be **two digits after the decimal dot**. --- ## List - Lists in Python are defined using square brackets, with the elements stored in the list separated by commas: ***list = ["This", "is", "a", "list"]***. - You can use the ***len()*** function to return the number of elements in a list: ***len(list)*** would return 4. --- ![](https://i.imgur.com/mWLQmwk.png) --- ![](https://i.imgur.com/njxgTia.png) --- ``` >>>animal_list = ["cat", "dog", "banana"] >>>"cat" in animal_list >>>"pig" in animal_list ``` --- You can access the first element in a list by doing ***list[0]***, which would allow you to access the string ***"cat"***. --- - In Python, lists and strings are quite similar. They’re both examples of sequences of data. - Sequences have similar properties, like - (1) being able to iterate over them using for loops; - (2) support indexing; - (3) using the len function to find the length of the sequence; - (4) using the plus operator + in order to concatenate; - (5) using the in keyword to check if the sequence contains a value. --- ### Modifying Lists - You can add elements to the end of a list using the ***append*** method. You call this method on a list using dot notation, and pass in the element to be added as a parameter. - For example, ***list.append("horse")*** would add the string "horse" to the end of the list called list. --- - If you want to add an element to a list in a specific position, you can use the method ***insert***. - The method takes two parameters: the first specifies the index in the list, and the second is the element to be added to the list. - So ***list.insert(0, "fish")*** would add the string "fish" to the front of the list. --- - You can remove elements from the list using the ***remove*** method. - This method takes an element as a parameter, and removes the first occurrence of the element. - If the element isn’t found in the list, you’ll get a ***ValueError*** error explaining that the element was not found in the list. --- - You can also remove elements from a list using the ***pop*** method. - This method differs from the remove method in that it takes an index as a parameter, and returns the element that was removed. --- - You can change an element in a list by using indexing to overwrite the value stored at the specified index. - For example, you can enter list[0] = "bird" to overwrite the first element in a list with the new string "bird". --- ### Enumerate - The ***enumerate()*** function takes a list as a parameter and returns a tuple for each element in the list. The first value of the tuple is the index and the second value is the element itself. ``` >>>animal_list = ["cat", "dog", "fish", "bird", "pig"] >>>for index, value in enumerate(animal_list): print(index, value) ... 0 cat 1 dog 2 fish 3 bird 4 pig ``` --- ## Dictionaries - Dictionaries are another data structure in Python. - They’re similar to a list in that they can be used to organize data into collections. - However, data in a dictionary isn't accessed based on its position. - Data in a dictionary is organized into pairs of ***keys*** and ***values***. You use ***the key*** to access the corresponding value. - Where a list index is always a number, a dictionary key can be a different data type, like a string, integer, float, or even tuples. --- ### Creating a dictionary - When creating a dictionary, you use curly brackets: ***{}***. --- ``` >>>animals = { "bears":10, "lions":1, "tigers":2 } >>>animals["bears"] ``` --- --- ### Adding and changing an element in a dictionary --- ``` >>>animals["zebras"] = 2 # add new key to the dictionary >>>animals["zebras"] = 10 # changing the value stored in the zebras key from 10 to 11 >>>del animals["bears"] # remove the key value pair from the animals dictionary ``` --- --- ### Iterating over dictionaries - Using the ***items*** method: ``` >>>for key, value in animals.items(): print(key, value) ... bears 10 lions 1 tigers 2 ``` - This method returns a tuple for each element in the dictionary, where the first element in the tuple is the key and the second is the value. --- - If you only wanted to access the keys in a dictionary, you could use the ***keys()*** method on the dictionary: ***dictionary.keys()***. - If you only wanted the values, you could use the ***values()*** method: ***dictionary.values()***. --- ### :fire: Homework: - (Optional) Build a cheat sheet for different types of formatting in Python. - What is a tuple? Build a tuple cheat sheet.
{"metaMigratedAt":"2023-06-16T23:03:22.457Z","metaMigratedFrom":"Content","title":"Session 3: Python 201","breaks":true,"contributors":"[{\"id\":\"c7c0a657-74ce-4c87-8beb-3ed25f434ff0\",\"add\":10017,\"del\":94}]"}
    197 views