Python Strings - Module 4 - Data Structures PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document is a tutorial about Python strings, including creating strings, using quotes, assigning strings to variables, multiline strings, working with strings as arrays, looping through strings, finding the length of strings, checking if strings contains specific characters or phrases and using string methods such as upper(), lower(), strip(), replace(), and split().
Full Transcript
**Module-IV: Data Structures** **Strings** Strings in python are surrounded by either single quotation marks, or double quotation marks. \'hello\' is the same as \"hello\". You can display a string literal with the print() function: Example print(\"Hello\")\ print(\'Hello\') **Quotes Inside Q...
**Module-IV: Data Structures** **Strings** Strings in python are surrounded by either single quotation marks, or double quotation marks. \'hello\' is the same as \"hello\". You can display a string literal with the print() function: Example print(\"Hello\")\ print(\'Hello\') **Quotes Inside Quotes** You can use quotes inside a string, as long as they don\'t match the quotes surrounding the string: Example print(\"It\'s alright\")\ print(\"He is called \'Johnny\'\")\ print(\'He is called \"Johnny\"\') **Assign String to a Variable** Assigning a string to a variable is done with the variable name followed by an equal sign and the string: Example a = \"Hello\"\ print(a) **Multiline Strings** You can assign a multiline string to a variable by using three quotes: Example You can use three double quotes: a = \"\"\"Lorem ipsum dolor sit amet,\ consectetur adipiscing elit,\ sed do eiusmod tempor incididunt\ ut labore et dolore magna aliqua.\"\"\"\ print(a) **Or three single quotes:** Example a = \'\'\'Lorem ipsum dolor sit amet,\ consectetur adipiscing elit,\ sed do eiusmod tempor incididunt\ ut labore et dolore magna aliqua.\'\'\'\ print(a) **Note:** in the result, the line breaks are inserted at the same position as in the code. **Strings are Arrays** Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. Example Get the character at position 1 (remember that the first character has the position 0): a = \"Hello, World!\"\ print(a\[1\]) **Looping Through a String:** Since strings are arrays, we can loop through the characters in a string, with a for loop. Example Loop through the letters in the word \"banana\": for x in \"banana\":\ print(x) **String Length:** To get the length of a string, use the len() function. Example The len() function returns the length of a string: a = \"Hello, World!\"\ print(len(a)) **Check String:** To check if a certain phrase or character is present in a string, we can use the keyword in. Example Check if \"free\" is present in the following text: txt = \"The best things in life are free!\"\ print(\"free\" in txt) Use it in an if statement: Example Print only if \"free\" is present: txt = \"The best things in life are free!\"\ if \"free\" in txt:\ print(\"Yes, \'free\' is present.\") **Check if NOT:** To check if a certain phrase or character is NOT present in a string, we can use the keyword not in. Example Check if \"expensive\" is NOT present in the following text: txt = \"The best things in life are free!\"\ print(\"expensive\" not in txt) Use it in an if statement: Example print only if \"expensive\" is NOT present: txt = \"The best things in life are free!\"\ if \"expensive\" not in txt:\ print(\"No, \'expensive\' is NOT present.\") Python has a set of built-in methods that you can use on strings. **Upper Case** Example The upper() method returns the string in upper case: a = \"Hello, World!\"\ print(a.upper()) **Lower Case** Example The lower() method returns the string in lower case: a = \"Hello, World!\"\ print(a.lower()) **Remove Whitespace:** Whitespace is the space before and/or after the actual text, and very often you want to remove this space. Example The strip() method removes any whitespace from the beginning or the end: a = \" Hello, World! \"\ print(a.strip()) \# returns \"Hello, World!\" **Replace String** Example The replace() method replaces a string with another string: a = \"Hello, World!\"\ print(a.replace(\"H\", \"J\")) **Split String** The split() method returns a list where the text between the specified separator becomes the list items. Example The split() method splits the string into substrings if it finds instances of the separator: a = \"Hello, World!\"\ print(a.split(\",\")) \# returns \[\'Hello\', \' World!\'\] **String Methods** Learn more about String Methods with our **Note:** All string methods return new values. They do not change the original string. **Method** **Description** ---------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- [[capitalize()]](https://www.w3schools.com/python/ref_string_capitalize.asp) Converts the first character to upper case [[casefold()]](https://www.w3schools.com/python/ref_string_casefold.asp) Converts string into lower case [[center()]](https://www.w3schools.com/python/ref_string_center.asp) Returns a centered string [[count()]](https://www.w3schools.com/python/ref_string_count.asp) Returns the number of times a specified value occurs in a string [[encode()]](https://www.w3schools.com/python/ref_string_encode.asp) Returns an encoded version of the string [[endswith()]](https://www.w3schools.com/python/ref_string_endswith.asp) Returns true if the string ends with the specified value [[expandtabs()]](https://www.w3schools.com/python/ref_string_expandtabs.asp) Sets the tab size of the string [[find()]](https://www.w3schools.com/python/ref_string_find.asp) Searches the string for a specified value and returns the position of where it was found [[format()]](https://www.w3schools.com/python/ref_string_format.asp) Formats specified values in a string format\_map() Formats specified values in a string [[index()]](https://www.w3schools.com/python/ref_string_index.asp) Searches the string for a specified value and returns the position of where it was found [[isalnum()]](https://www.w3schools.com/python/ref_string_isalnum.asp) Returns True if all characters in the string are alphanumeric [[isalpha()]](https://www.w3schools.com/python/ref_string_isalpha.asp) Returns True if all characters in the string are in the alphabet [[isascii()]](https://www.w3schools.com/python/ref_string_isascii.asp) Returns True if all characters in the string are ascii characters [[isdecimal()]](https://www.w3schools.com/python/ref_string_isdecimal.asp) Returns True if all characters in the string are decimals [[isdigit()]](https://www.w3schools.com/python/ref_string_isdigit.asp) Returns True if all characters in the string are digits [[isidentifier()]](https://www.w3schools.com/python/ref_string_isidentifier.asp) Returns True if the string is an identifier [[islower()]](https://www.w3schools.com/python/ref_string_islower.asp) Returns True if all characters in the string are lower case [[isnumeric()]](https://www.w3schools.com/python/ref_string_isnumeric.asp) Returns True if all characters in the string are numeric [[isprintable()]](https://www.w3schools.com/python/ref_string_isprintable.asp) Returns True if all characters in the string are printable [[isspace()]](https://www.w3schools.com/python/ref_string_isspace.asp) Returns True if all characters in the string are whitespaces [[istitle()]](https://www.w3schools.com/python/ref_string_istitle.asp) Returns True if the string follows the rules of a title [[isupper()]](https://www.w3schools.com/python/ref_string_isupper.asp) Returns True if all characters in the string are upper case [[join()]](https://www.w3schools.com/python/ref_string_join.asp) Joins the elements of an iterable to the end of the string [[ljust()]](https://www.w3schools.com/python/ref_string_ljust.asp) Returns a left justified version of the string [[lower()]](https://www.w3schools.com/python/ref_string_lower.asp) Converts a string into lower case [[lstrip()]](https://www.w3schools.com/python/ref_string_lstrip.asp) Returns a left trim version of the string [[maketrans()]](https://www.w3schools.com/python/ref_string_maketrans.asp) Returns a translation table to be used in translations [[partition()]](https://www.w3schools.com/python/ref_string_partition.asp) Returns a tuple where the string is parted into three parts [[replace()]](https://www.w3schools.com/python/ref_string_replace.asp) Returns a string where a specified value is replaced with a specified value [[rfind()]](https://www.w3schools.com/python/ref_string_rfind.asp) Searches the string for a specified value and returns the last position of where it was found [[rindex()]](https://www.w3schools.com/python/ref_string_rindex.asp) Searches the string for a specified value and returns the last position of where it was found [[rjust()]](https://www.w3schools.com/python/ref_string_rjust.asp) Returns a right justified version of the string [[rpartition()]](https://www.w3schools.com/python/ref_string_rpartition.asp) Returns a tuple where the string is parted into three parts [[rsplit()]](https://www.w3schools.com/python/ref_string_rsplit.asp) Splits the string at the specified separator, and returns a list [[rstrip()]](https://www.w3schools.com/python/ref_string_rstrip.asp) Returns a right trim version of the string [[split()]](https://www.w3schools.com/python/ref_string_split.asp) Splits the string at the specified separator, and returns a list [[splitlines()]](https://www.w3schools.com/python/ref_string_splitlines.asp) Splits the string at line breaks and returns a list [[startswith()]](https://www.w3schools.com/python/ref_string_startswith.asp) Returns true if the string starts with the specified value [[strip()]](https://www.w3schools.com/python/ref_string_strip.asp) Returns a trimmed version of the string [[swapcase()]](https://www.w3schools.com/python/ref_string_swapcase.asp) Swaps cases, lower case becomes upper case and vice versa [[title()]](https://www.w3schools.com/python/ref_string_title.asp) Converts the first character of each word to upper case [[translate()]](https://www.w3schools.com/python/ref_string_translate.asp) Returns a translated string [[upper()]](https://www.w3schools.com/python/ref_string_upper.asp) Converts a string into upper case [[zfill()]](https://www.w3schools.com/python/ref_string_zfill.asp) Fills the string with a specified number of 0 values at the beginning List: ----- Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are [Tuple](https://www.w3schools.com/python/python_tuples.asp), [Set](https://www.w3schools.com/python/python_sets.asp), and [Dictionary](https://www.w3schools.com/python/python_dictionaries.asp), all with different qualities and usage. Lists are created using square brackets: ### Example Create a List: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ print(thislist) 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. **Note:** There are some [list methods](https://www.w3schools.com/python/python_lists_methods.asp) that will change the order, but in general: the order of the items will not change. 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 Lists allow duplicate values: thislist = \[\"apple\", \"banana\", \"cherry\", \"apple\", \"cherry\"\]\ print(thislist) List Length ----------- To determine how many items a list has, use the len() function: ### Example Print the number of items in the list: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ print(len(thislist)) List Items - Data Types ----------------------- List items can be of any data type: ### Example String, int and boolean data types: list1 = \[\"apple\", \"banana\", \"cherry\"\]\ list2 = \[1, 5, 7, 9, 3\]\ list3 = \[True, False, False\] **A list can contain different data types:** ### Example A list with strings, integers and boolean values: list1 = \[\"abc\", 34, True, 40, \"male\"\] type() ------ From Python\'s perspective, lists are defined as objects with the data type \'list\': \ ### Example What is the data type of a list? mylist = \[\"apple\", \"banana\", \"cherry\"\]\ print(type(mylist)) The list() Constructor ---------------------- It is also possible to use the list() constructor when creating a new list. ### Example Using the list() constructor to make a List: thislist = list((\"apple\", \"banana\", \"cherry\")) \# note the double round-brackets\ print(thislist) Python Collections (Arrays) --------------------------- There are four collection data types in the Python programming language: - **List** is a collection which is ordered and changeable. Allows duplicate members. - [**Tuple**](https://www.w3schools.com/python/python_tuples.asp) is a collection which is ordered and unchangeable. Allows duplicate members. - [**Set**](https://www.w3schools.com/python/python_sets.asp) is a collection which is unordered, unchangeable\*, and unindexed. No duplicate members. - [**Dictionary**](https://www.w3schools.com/python/python_dictionaries.asp) is a collection which is ordered\*\* and changeable. No duplicate members. \*Set *items* are unchangeable, but you can remove and/or add items whenever you like. \*\*As of Python version 3.7, dictionaries are *ordered*. In Python 3.6 and earlier, dictionaries are *unordered*. When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security. Access Items ------------ List items are indexed and you can access them by referring to the index number: ### Example[Get your own Python Server](https://www.w3schools.com/python/python_server.asp) Print the second item of the list: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ print(thislist\[1\]) **Note: **The first item has index 0. ### Negative Indexing Negative indexing means start from the end -1 refers to the last item, -2 refers to the second last item etc. ### Example Print the last item of the list: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ print(thislist\[-1\]) ### 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. ### Example Return the third, fourth, and fifth item: thislist = \[\"apple\", \"banana\", \"cherry\", \"orange\", \"kiwi\", \"melon\", \"mango\"\]\ print(thislist\[2:5\]) **Note:** The search will start at index 2 (included) and end at index 5 (not included).Remember that the first item has index 0. By leaving out the start value, the range will start at the first item: ### Example This example returns the items from the beginning to, but NOT including, \"kiwi\": thislist = \[\"apple\", \"banana\", \"cherry\", \"orange\", \"kiwi\", \"melon\", \"mango\"\]\ print(thislist\[:4\]) By leaving out the end value, the range will go on to the end of the list: ### Example This example returns the items from \"cherry\" to the end: thislist = \[\"apple\", \"banana\", \"cherry\", \"orange\", \"kiwi\", \"melon\", \"mango\"\]\ print(thislist\[2:\]) ### Range of Negative Indexes: Specify negative indexes if you want to start the search from the end of the list: ### Example This example returns the items from \"orange\" (-4) to, but NOT including \"mango\" (-1): thislist = \[\"apple\", \"banana\", \"cherry\", \"orange\", \"kiwi\", \"melon\", \"mango\"\]\ print(thislist\[-4:-1\]) Check if Item Exists -------------------- To determine if a specified item is present in a list use the in keyword: ### Example Check if \"apple\" is present in the list: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ if \"apple\" in thislist:\ print(\"Yes, \'apple\' is in the fruits list\") Change Item Value ----------------- To change the value of a specific item, refer to the index number: ### Example Change the second item: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thislist\[1\] = \"blackcurrant\"\ print(thislist) Change a Range of Item Values ----------------------------- To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values: ### Example Change the values \"banana\" and \"cherry\" with the values \"blackcurrant\" and \"watermelon\": thislist = \[\"apple\", \"banana\", \"cherry\", \"orange\", \"kiwi\", \"mango\"\]\ thislist\[1:3\] = \[\"blackcurrant\", \"watermelon\"\]\ print(thislist) If you insert *more* items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly: ### Example Change the second value by replacing it with *two* new values: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thislist\[1:2\] = \[\"blackcurrant\", \"watermelon\"\]\ print(thislist) **Note:** The length of the list will change when the number of items inserted does not match the number of items replaced. If you insert *less* items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly: ### Example Change the second and third value by replacing it with *one* value: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thislist\[1:3\] = \[\"watermelon\"\]\ print(thislist) Insert Items ------------ To insert a new list item, without replacing any of the existing values, we can use the insert() method. The insert() method inserts an item at the specified index: ### Example Insert \"watermelon\" as the third item: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thislist.insert(2, \"watermelon\")\ print(thislist) **Note:** As a result of the example above, the list will now contain 4 items. Append Items ------------ To add an item to the end of the list, use the append() method: ### Example Using the append() method to append an item: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thislist.append(\"orange\")\ print(thislist) Insert Items ------------ To insert a list item at a specified index, use the insert() method. The insert() method inserts an item at the specified index: ### Example Insert an item as the second position: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thislist.insert(1, \"orange\")\ print(thislist) **Note:** As a result of the examples above, the lists will now contain 4 items. Extend List ----------- To append elements from *another list* to the current list, use the extend() method. ### Example Add the elements of tropical to thislist: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ tropical = \[\"mango\", \"pineapple\", \"papaya\"\]\ thislist.extend(tropical)\ print(thislist) The elements will be added to the *end* of the list. Add Any Iterable ---------------- The extend() method does not have to append *lists*, you can add any iterable object (tuples, sets, dictionaries etc.). ### Example Add elements of a tuple to a list: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thistuple = (\"kiwi\", \"orange\")\ thislist.extend(thistuple)\ print(thislist) Remove Specified Item --------------------- The remove() method removes the specified item. ### Example Remove \"banana\": thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thislist.remove(\"banana\")\ print(thislist) If there are more than one item with the specified value, the remove() method removes the first occurrence: ### Example Remove the first occurrence of \"banana\": thislist = \[\"apple\", \"banana\", \"cherry\", \"banana\", \"kiwi\"\]\ thislist.remove(\"banana\")\ print(thislist) Remove Specified Index ---------------------- The pop() method removes the specified index. ### Example Remove the second item: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thislist.pop(1)\ print(thislist) If you do not specify the index, the pop() method removes the last item. ### Example Remove the last item: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thislist.pop()\ print(thislist) The del keyword also removes the specified index: ### Example Remove the first item: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ del thislist\[0\]\ print(thislist) The del keyword can also delete the list completely. ### Example Delete the entire list: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ del thislist Clear the List -------------- The clear() method empties the list. The list still remains, but it has no content. ### Example Clear the list content: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ thislist.clear()\ print(thislist) Loop Through a List ------------------- You can loop through the list items by using a for loop: ### Example Print all items in the list, one by one: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ for x in thislist:\ print(x) Loop Through the Index Numbers ------------------------------ You can also loop through the list items by referring to their index number. Use the range() and len() functions to create a suitable iterable. ### Example Print all items by referring to their index number: thislist = \[\"apple\", \"banana\", \"cherry\"\]\ for i in range(len(thislist)):\ print(thislist\[i\]) The iterable created in the example above is \[0, 1, 2\]. Using a While Loop ------------------ You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration. ### Example Print all items, using a while loop to go through all the index numbers thislist = \[\"apple\", \"banana\", \"cherry\"\]\ i = 0\ while i \