1/57
Week 6-10 strings, functions, dictionaries
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
strings
sequences of characters (words, sentences, symbols)
written with single (' ') , double (" ") quotes or triple quotes.
Strings can be stored in variables, or printed
triple quotes
""" ... """
used for multiline strings
multi line strings
Use triple quotes (""" ... """) for multi-line strings.
● Easier for long text or formatted stories.
● For typing a long string, it’s sometimes best to type the string across multiple lines (also
known as line breaks) so that the string is easier to read in the program
escape characters
let us include special symbols (apostrophes, quotes, new lines,)
inside strings.
Handle special characters inside strings without causing errors
a backslash followed by the character we
want to use
\n
new line
f strings
used to insert variable values directly. (format: f"This is a variable {variable}.")
+
Concatenation combines strings using the + operator
capitalize()
capitalize first letter
replace()
print(input.replace('x', 'y'))
replace parts of string
replaces x with y
len()
count characters
upper()
convert to uppercase
lower()
convert to lowercase
strip()
remove extra characters/spaces
title()
capitalize each word
{#:.2f}
prints number to 2 decimal places in f string
<
print(f"{'x':<#}")
left-aligned
>
print(f"{'x':>#}")
right-aligned
^
print(f"{"x":^#}")
centered
d for int, f for float, s for string
type format
endswith(suffix)
Returns True or False depending on whether the string ends with the given suffix
join(sequence)
Joins the sequence of strings into one string, using the “called-on” string as the separator
split(sep, [maxsplit=-1])
Splits a string into a list of substrings, using the given separator.
find(sub, [start, [end]])
Returns the index (position) where substring sub can be found in the string. Returns -1 if not found
center(width, [fillchar])
Centers the string between the given fill characters
isalnum()
returns whether the string is all alphanumeric (both letters and numbers)
returns True or False
isalpha()
returns whether the string is all alphabetic
returns True or False
isdigit()
returns whether the string is all digits
returns True or False
islower()
returns whether the string is all lowercase
returns True or False
isupper()
returns whether the string is all uppercase
returns True or False
rfind(sub, [start, [end]])
Returns the index where substring sub can be found in the string, searching from right to left.
Returns -1 if not found.
startswith(prefix)
Returns whether the string starts with the given prefix
True or False
alternate form
print(f"{10:#b}") # '0b1010' (binary with prefix)
print(f"{10:#x}") # '0xa' (hexadecimal with prefix)
print(f"{10:#o}") # '0o12' (octal with prefix)
abs()
Computes the absolute value (numerical).
pow()
power = pow(x,y)
Computes the first value raised to the power of the second value
raises x to the power of y
lambda
keyword that defines the anonymous function
quick, temporary ("throwaway") function — something
short enough to write in one line and not meant to be reused elsewhere
objects
(complex types like lists):
→ Only a pointer/reference is stored; the actual data lives in memory (heap).
→ Functions can modify these objects
primitive type
int, float, bool, str
→ Values stored directly in memory
add = lambda x,y: x+y
print(add(#,#)
lambda example adding
function body
contains whatever actions you
choose to have your function complete
call function
function()
To call a function, write its name followed by parentheses
return
statement to end a function, at the end of the actions within the function body,
which can include an expression/ optionally send a value back
parameter
lets you pass data/values into a function.
Values you pass when calling the function are arguments; Python takes the arguments and
assigns them to the variables named by the parameters
dictionary
a list of named values, which means that each item in the list consists of a key
and a value, often referred to as a key-value pair
Keys must be unique in the dictionary and can be quoted strings, numbers, or tuples.
Each key can have any value of any type. The items inside a dictionary are separated by
commas
uses curly brackets {}
dictionary = {key : value, key : value}
dictionary format
print(dictionary[key])
The value of the keys inside a dictionary can be accessed by referencing the key name using
brackets.
dictionary[key] = value
Add an item by referencing a new key and assigning its value
pop(), popitem(), del
three ways to remove items from a dictionary
dictionary.pop(‘x’)
removes x from dictionary
popitem()
removes last item
for key in dictionary:
print(key)
Print all keys in dictionary using for loop
for value in dictionary:
print(dictionary[value]:
print all values in dictionary using for loop
for x in dictionary.values():
print(x)
print all values in dictionary
for x, y in dictionary.items():
print(x, y)
print all key:alue pairs in a dictionary using for loop
dictionary = { “nested1”: { key1: value1, key2: value2},
“nested2” : { key3: value3, key4: value4}}
nested dictionary format
print(dictionary["nested"]["key"])
Access items in a nested dictionary
dictionary["nested"]["key"] = "value"
Add item in a nested dictionary:
for key, value in dictionary.items():
print(key, value)
loop through nested dictionary
dictionary = {}
for i in range(2):
key = input(" enter:")
value = int(input("enter:"))
dictioanry[key] = value
adds input to a dictionary loop for 2 rounds