CSE 120 - PYTHON PROGRAMMING Module – 2 part 1 SESSION IMPOTANT TOPICS String Manipulation Lists Tuple Dictionaries String manipulation in Python A string is a sequence of characters. How to create a string in Python? Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings. How to access characters in a string? We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError. The index must be an integer. We can't use floats or other types, this will result into TypeError. Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a string by using the slicing operator :(colon). Slicing can be best visualized by considering the index to be between the elements as shown below. If we want to access a range, we need the index that will slice the portion from the string. Python String Slicing We can extend the square bracket notation to access a substring(slice) of a string. We can specify start, stop and step(optional) within the square brackets as: my_string[start:stop:step] start: It is the index from where the slice starts. The default value is 0. stop: It is the index at which the slice stops. The character at this index is not included in the slice. The default value is the length of the string. step: It specifies the number of jumps to take while going from start to stop. It takes the default value of 1. How to change or delete a string? Strings are immutable. This means that elements of a string cannot be changed once they have been assigned. We can simply reassign different strings to the same name. Python String Operations There are many operations that can be performed with strings which makes it one of the most used data types in Python. Concatenation of Two or More Strings Joining of two or more strings into a single one is called concatenation. The + operator does this in Python. Simply writing two string literals together also concatenates them. String Membership Test We can test if a substring exists within a string or not, using the keyword in. #simple print output hello world. I'm Python. This is "Awesome" #with new line and tab "First Line" Second Line Third Line with Tab #string operations Add 2 strings : Python Program Repeat string : PythonPythonPythonPythonPython 2nd character in a word : y last character in a word : n Text from a position : thon Text until a position : Pyt Text From-To a position : ho Text Remove last char : Pyth Text all but step size diff : Pto Text all but step size diff recerse: nohtyP Text to upper : PYTHON Text to lower : python Text split : ['Pyt', 'on'] #label and variable a is 10 a * 10 = 100 and a * 2 = 20 Length of a String - len : 6 PYTHON STRING METHODS Python has a set of built-in methods that you can use on strings. Note: All string methods returns new values. They do not change the original string. Function Description mystring[:N] Extract N number of characters from start of string. mystring[-N:] Extract N number of characters from end of string Extract characters from middle of string, starting from X position mystring[X:Y] and ends with Y str.split(sep=' ') Split Strings str.replace(old_substring, new_substring) Replace a part of text with different sub-string str.lower() Convert characters to lowercase str.upper() Convert characters to uppercase str.count('sub_string') Count occurence of pattern in string str.find( ) Return position of sub-string or pattern str.isalnum() Check whether string consists of only alphanumeric characters str.islower() Check whether characters are all lower case str.isupper() Check whether characters are all upper case str.isnumeric() Check whether string consists of only numeric characters str.isspace() Check whether string consists of only whitespace characters len( ) Calculate length of string cat( ) Concatenate Strings (Pandas Function) separator.join(str) Concatenate Strings PYTHON LISTS A list in Python is used to store the sequence of various types of data. Python lists are mutable type its mean we can modify its element after it created. However, Python consists of six data-types that are capable to store the sequences, but the most common and reliable type is the list. A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets []. A list can be define as below L1 = ["John", 102, "USA"] L2 = [1, 2, 3, 4, 5, 6] CHARACTERISTICS OF LISTS The list has the following characteristics: The lists are ordered. The element of the list can access by index. The lists are the mutable type. A list can store the number of various elements. List indexing and splitting The indexing is processed in the same way as it happens with the strings. The elements of the list can be accessed by using the slice operator []. The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so on. We can get the sub-list of the list using the following syntax. list_varible(start:stop:step) The start denotes the starting index position of the list. The stop denotes the last index position of the list. The step is used to skip the nth element within a start:stop Consider the following example: Updating List values • Lists are the most versatile data structures in Python since they are mutable, and their values can be updated by using the slice and assignment operator. • Python also provides append() and insert() methods, which can be used to add values to the list. • Consider the following example to update the values inside the list. Python List Operations • The concatenation (+) and repetition (*) operators work in the same way as they were working with the strings. Let's see how the list responds to various operators. List Items List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc. Ordered When we say that lists are ordered, it means that the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list. Changeable The list is changeable, meaning that we can change, add, and remove items in a list after it has been created. Allow Duplicates Since lists are indexed, lists can have items with the same value: Example: List Length To determine how many items a list has, use the len() function: Range of Indexes You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new list with the specified items.