Pro lang 2 Flashcards
Assign Multiple Values
VD 1: x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z)
VD 2: x = y = z = "Orange" print(x) print(y) print(z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you extract the values into variables. This is called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"] x, y, z = fruits print(x) print(y) print(z)
Global Variables
- Variables that are created outside of a function (as in all of the examples above)
- can be used by everyone, both inside of functions and outside
Create a variable outside of a function, and use it inside the function
Create a variable inside a function, with the same name as the global variable
VD 1
x = “awesome”
def myfunc(): print("Python is " + x)
myfunc()
VD 2:
x = “awesome”
def myfunc(): x = "fantastic" print("Python is " + x)
myfunc()
print(“Python is “ + x)
The global Keyword
If you use the global keyword, the variable belongs to the global scope:
def myfunc(): global x x = "fantastic"
myfunc()
print(“Python is “ + x)
Type Conversion
x = 1 # int
a = float(x)
print(type(a))
Strings are Arrays
Example
Get the character at position 1 (remember that the first character has the position 0):
a = “Hello, World!”
print(a[1])
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)
——————————————————–
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)
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = “Hello, World!”
print(b[2:5])/#from start: b[:5]; #to end: b[2:]
Upper Case/ lower case
The upper() method returns the string in upper case:
a = “Hello, World!”
print(a.upper())
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 Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
a = “Hello”
b = “World”
c = a + b
print(c)
String Format
The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are:
Example
Use the format() method to insert numbers into strings:
age = 36
txt = “My name is John, and I am {}”
print(txt.format(age))
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by double quotes:
Escape Characters
Code Result \' Single Quote \\ Backslash \n New Line \r Carriage Return \t Tab \b Backspace \f Form Feed \ooo Octal value \xhh Hex value
STRING METHODS
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
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, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
Example
Create a List:
thislist = [“apple”, “banana”, “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))