1/37
wek 5 & 6
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
strings
sequence of characters
example x = “zenora is a girl”
Since strings are objects, they come with built-in methods:
text = "hello world"
text.upper() # '“HELLO WORLD”
text.lower() # “hello world”
text.capitalize() #" “Hello World”
text.replace(old word, the replacement)
text.replace(“world”, “you”) # “hello you”
text.split() #[“hello”, “world”
text.strip() …. removes spaces before and after the text never in the middle # “hello”
datatype of string
string
Other related methods
.lstrip() removes spaces on the left
.rstrip() removes spaces on the right
strip vs slicing
.strip() removes whitespaces
slicing extract part of string using indexex
Characters Are Numbers Internally
A = 65
a = 97
ord(‘a’) = 97
char(65) = A
unicode
text = "Hello World"
print([ord(a) for a in text])]
#[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
processing string
+ to join string “hello” + “world”
# “hello world”
to repeat string “hello”*3
hellohellohello
to find the length len() # 5
Indexing a string
strings are immutable
“hello Zee”[6] = Z
what you cannot do
s = "Hello"
s[0] = "Y" # ❌ This will raise an error!
you can do this
s = "Hello"
s = "Y" + s[1:] # Now s = "Yello"
Iterating over string characters
word = "Hello"
for a_char in word:
print(a_char * 2, end="")
word = "Hello"
for index in range(len(word)):
print(word[index] * 2, end="")
string slicing vs string indexing
slicing Syntax: string[start
⏹step]
s[0, 10, 2] this gets a substring
indexing
Syntax: string[index]
s[4] this gets one character
Notes on String Slicing
s[start, stop, step]
if the step is negative
reverse the string
To change a sentence to a list,
you use split
sentence = "I love learning new things"
word_list = sentence.split()
print(word_list)
sentence = "Apples, oranges, bananas, grapes"
item_list = sentence.split(", ")
print(item_list)
x.split(you write whatever is separating the sentence)
to turn a word into a list
you use list(sentence)
sentence = "Hello"
char_list = list(sentence)
print(char_list)
[“h”, “e”, “l”, “l”, “o”]
string methods THEY ARE ALL CASE SENSETIVE
s.count()
count how many times an item appear in the string
s = "banana"
print(s.count("a")) # Output: 3
s.find()
find the first occurrence
s = "hello world"
print(s.find("world")) # Output: 6
len()
return the length of the string
s.replace(old, new)
replace old string with new string
.REPLACE IS CASE SENSENTIVE
s = "I like apples"
print(s.replace("apples", "oranges")) # Output: "I like oranges"
string formatting
General Syntax:
"<template string>".format(<var1>, <var2>, ...)
name = "Alice"
age = 30
formatted = "My name is {} and I am {} years old.".format(name, age)
print(formatted)
"{} is {} years old.".format("Bob", 25)
"{1} is older than {0}.".format("Tom", "Jerry")
# Output: Jerry is older than Tom.
"Hello, {first} {last}!".format(first="John", last="Doe")
f-strings
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
Percent (%) formatting – Older style
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
Percent (%)
Code | Meaning | Example |
---|---|---|
| String |
|
| Integer (whole number) |
|
Left-Aligned in Fixed Width Using .format()
"{0:<20}".format("one")
Right-aligned:)
“{0:>20}”.format(“one”)
Center-aligned
“{0:20}”.format(“one”)
Floating point number rounding
{position:width.decimal place}
{0:5.3f}
print("|{0:5.3f}|".format(1.23456789))
|1.235|
print("|{0:8.3f}|".format(1.23456789))
| 1.235|
built in functions
print()
– displays output
round()
– rounds a number
len()
– returns the length of a sequence
type()
– returns the data type
map
def square(x):
return x * x
numbers = [1, 2, 3, 4]
squared = map(square, numbers)
print(list(squared)) # Output: [1, 4, 9, 16]
Defining a Function
def some_function():
statement1
statement2
# More statements as needed
calling or evoking a functions
some_function()
parameters
actual parameters/arguments
these are the real values you pass in when calling a function
greet("Alice") # "Alice" is the actual parameter (argument)
greet("Bob") # "Bob" is also an actual parameter
formal parameters
these act like placeholders
def greet(name): # 'name' is a formal parameter
print("Hello", name)
Pass-By-Value
def change_value(x):
print("Before changing inside function:", x)
x = 99
print("After changing inside function:", x)
num = 10
print("Before function call:", num)
change_value(num)
print("After function call:", num)
pass by value
def some_function(a):
a = a + 1
print(a)
b = 12
some_function(b)
print(b)
local variable
def some_function():
a = 1 # 'a' is a local variable inside the function
print(a) # prints the value of 'a'
some_function() # calls the function, so it will print 1
global
?
Return Values
def add(a, b):
return a + b # returns the sum of a and b
result = add(10, 11)
print(result) # Output: 21
docstring
used to document what a function does
"""triple quotes"""
to access the docstring use function_name._doc_
def greet(name):
"""
Greets the user with the provided name.
Parameters:
name (str): The name of the user.
Returns:
None
"""
print(f"Hello, {name}!")
you can for the doc string
print(greet.__doc__)
output
Greets the user with the provided name.
Parameters:
name (str): The name of the user.
Returns:
None
Nested Functions / Function Composition
function inside function
def cube(x):
return x x x
def square(x):
return x * x
def power(a, b):
return a ** b
print(power(cube(2), square(2)))
International Space Station
first component was launched in 1998
largest man made object at orbit
can be seen with naked eye.
arrays in functions
def tester(myArr):
print("In function, before append", myArr)
myArr.append('a') # modifies the original list (mutates it)
print("In function, after append", myArr)
myArr = ['a', 'b', 'c'] # reassigns local variable 'myArr' to a new list
print("In function, after reassignment", myArr)
arrMain = ["one", "two", "three"]
print("Before function call", arrMain)
tester(arrMain)
print("After function call", arrMain)
Before function call ['one', 'two', 'three']
In function, before append ['one', 'two', 'three']
In function, after append ['one', 'two', 'three', 'a']
In function, after reassignment ['a', 'b', 'c']
After function call ['one', 'two', 'three', 'a']
Enigma
function
def Enigma(lst, item):
tmp = []
for i in lst:
if i != item:
tmp.append(i)
return tmp
def main():
list1 = [2, 4, 6, 6, 8, 10]
list2 = ["Skipper", "Kowalski", "Rico", "Private", "King Julian"]
list3 = [[1, 2], [3, 4], [5, 6]]
print(Enigma(list2, "King Julian"))
['Skipper', 'Kowalski', 'Rico', 'Private']
[2, 4, 6, 6, 8, 10]