Knowledge in Python

String Methods

String MethodsPython has a set of built-in methods that you can use on strings.ExampleThe strip() method removes any whitespace from the beginning or the end: a = " Hello, World! " print(a.strip()) # returns "Hello, World!" ExampleThe lower() method returns the string in lower case: a = "Hello, World!" print(a.lower()) ExampleThe upper() method returns the string in upper case: a = "Hello, World!" print(a.upper()) ExampleThe replace() method replaces a string with another string: a = "Hello, World!" print(a.replace("H", "J")) ExampleThe split() method splits the string into substrings if it finds instances of the separator: a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!']

Check String

Check StringTo check if a certain phrase or character is present in a string, we can use the keywords in or not in.ExampleCheck if the phrase "ain" is present in the following text: txt = "The rain in Spain stays mainly in the plain"x = "ain" in txt print(x) ExampleCheck if the phrase "ain" is NOT present in the following text: txt = "The rain in Spain stays mainly in the plain"x = "ain" not in txt print(x) String ConcatenationTo concatenate, or combine, two strings you can use the + operator.ExampleMerge variable a with variable b into variable c: a = "Hello"b = "World"c = a + b print(c) ExampleTo add a space between them, add a " ": a = "Hello"b = "World"c = a + " " + b print(c)

String Format

String FormatAs we learned in the Python Variables chapter, we cannot combine strings and numbers like this:Example age = 36txt = "My name is John, I am " + ageprint(txt) But we can combine strings and numbers by using the format() method!The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:ExampleUse the format() method to insert numbers into strings: age = 36txt = "My name is John, and I am {}"print(txt.format(age)) The format() method takes unlimited number of arguments, and are placed into the respective placeholders:Example quantity = 3itemno = 567price = 49.95myorder = "I want {} pieces of item {} for {} dollars."print(myorder.format(quantity, itemno, price)) You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:Example quantity = 3itemno = 567price = 49.95myorder = "I want to pay {2} dollars for {0} pieces of item {1}."print(myorder.format(quantity, itemno, price))

Python Booleans

Python BooleansBooleans represent one of two values: True or False.Boolean ValuesIn programming you often need to know if an expression is True or False.You can evaluate any expression in Python, and get one of two answers, True or False.When you compare two values, the expression is evaluated and Python returns the Boolean answer:Example print(10 > 9)print(10 == 9)print(10 < 9) When you run a condition in an if statement, Python returns True or False:ExamplePrint a message based on whether the condition is True or False: a = 200b = 33if b > a: print("b is greater than a") else: print("b is not greater than a") Evaluate Values and VariablesThe bool() function allows you to evaluate any value, and give you True or False in return,ExampleEvaluate a string and a number: print(bool("Hello"))print(bool(15)) ExampleEvaluate two variables: x = "Hello"y = 15print(bool(x))print(bool(y))

Most Values are True

Most Values are TrueAlmost any value is evaluated to True if it has some sort of content.Any string is True, except empty strings.Any number is True, except 0.Any list, tuple, set, and dictionary are True, except empty ones.ExampleThe following will return True: bool("abc")bool(123)bool(["apple", "cherry", "banana"]) Some Values are FalseIn fact, there are not many values that evaluates to False, except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to False.ExampleThe following will return False: bool(False)bool(None)bool(0)bool("")bool(())bool([]) bool({}) One more value, or object in this case, evaluates to False, and that is if you have an objects that are made from a class with a __len__ function that returns 0 or False:Example class myclass(): def __len__(self):   return 0 myobj = myclass()print(bool(myobj))

Functions can Return a Boolean

Functions can Return a BooleanPython also has many built-in functions that returns a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:ExampleCheck if an object is an integer or not: x = 200print(isinstance(x, int))

Python Operators

Python OperatorsOperators are used to perform operations on variables and values.Python divides the operators in the following groups:Arithmetic operatorsAssignment operatorsComparison operatorsLogical operatorsIdentity operatorsMembership operatorsBitwise operators

Python Lists

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 is a collection which is ordered and unchangeable. Allows duplicate members.Set is a collection which is unordered and unindexed. No duplicate members.Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.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.ListA list is a collection which is ordered and changeable. In Python lists are written with square brackets.ExampleCreate a List: thislist = ["apple", "banana", "cherry"] print(thislist)

Access Items

Access Itemsou access the list items by referring to the index number:ExamplePrint the second item of the list: thislist = ["apple", "banana", "cherry"] print(thislist[1]) Negative IndexingNegative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.ExamplePrint the last item of the list: thislist = ["apple", "banana", "cherry"] print(thislist[-1]) Range of IndexesYou 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.ExampleReturn the third, fourth, and fifth item: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5])

Range of Negative Indexes

Range of Negative IndexesSpecify negative indexes if you want to start the search from the end of the list:ExampleThis example returns the items from index -4 (included) to index -1 (excluded) thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[-4:-1]) Change Item ValueTo change the value of a specific item, refer to the index number:ExampleChange the second item: thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist)

Loop Through a List

Loop Through a ListYou can loop through the list items by using a for loop:ExamplePrint all items in the list, one by one: thislist = ["apple", "banana", "cherry"] for x in thislist: print(x) You will learn more about for loops in our Python For Loops Chapter.Check if Item ExistsTo determine if a specified item is present in a list use the in keyword:ExampleCheck if "apple" is present in the list: thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list") List LengthTo determine how many items a list has, use the len() method:ExamplePrint the number of items in the list: thislist = ["apple", "banana", "cherry"] print(len(thislist)) Add ItemsTo add an item to the end of the list, use the append() method:ExampleUsing the append() method to append an item: thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist)

Remove Item

Remove ItemThere are several methods to remove items from a list:ExampleThe remove() method removes the specified item: thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) ExampleThe pop() method removes the specified index, (or the last item if index is not specified): thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist) ExampleThe del keyword removes the specified index: thislist = ["apple", "banana", "cherry"] del thislist[0]print(thislist) ExampleThe del keyword can also delete the list completely: thislist = ["apple", "banana", "cherry"] del thislist ExampleThe clear() method empties the list: thislist = ["apple", "banana", "cherry"] thislist.clear()print(thislist)