strings and functions

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/37

flashcard set

Earn XP

Description and Tags

wek 5 & 6

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

38 Terms

1
New cards

strings

sequence of characters

example x = “zenora is a girl”

2
New cards

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”

3
New cards

datatype of string

string

4
New cards

Other related methods

.lstrip() removes spaces on the left

.rstrip() removes spaces on the right

5
New cards

strip vs slicing

.strip() removes whitespaces

slicing extract part of string using indexex

6
New cards

Characters Are Numbers Internally

A = 65

a = 97

ord(‘a’) = 97

char(65) = A

7
New cards

unicode

  • text = "Hello World"

    print([ord(a) for a in text])]

  • #[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

8
New cards

processing string

  • + to join string “hello” + “world”

    # “hello world”

  • to repeat string “hello”*3

    hellohellohello

  • to find the length len() # 5

9
New cards

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"

10
New cards

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="")

11
New cards

string slicing vs string indexing

  • slicing Syntax: string[startstep]

  • s[0, 10, 2] this gets a substring

  • indexing Syntax: string[index]

  • s[4] this gets one character

12
New cards

Notes on String Slicing

s[start, stop, step]

  • if the step is negative

    reverse the string

13
New cards

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)

14
New cards

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”]

15
New cards

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"

16
New cards

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")

17
New cards

f-strings

name = "Alice"

age = 30

print(f"My name is {name} and I am {age} years old.")

18
New cards

Percent (%) formatting – Older style

name = "Alice"

age = 30

print("My name is %s and I am %d years old." % (name, age))

19
New cards

Percent (%)

Code

Meaning

Example

%s

String

"Hello, %s" % "Alice"

%d

Integer (whole number)

"Age: %d" % 2

20
New cards

Left-Aligned in Fixed Width Using .format()

"{0:<20}".format("one")

one———————

21
New cards

Right-aligned:)

“{0:>20}”.format(“one”)

—————————one

22
New cards

Center-aligned

“{0:20}”.format(“one”)

————one—————

23
New cards

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|

24
New cards

built in functions

  • print() – displays output

  • round() – rounds a number

  • len() – returns the length of a sequence

  • type() – returns the data type

25
New cards

map

def square(x):

return x * x

numbers = [1, 2, 3, 4]

squared = map(square, numbers)

print(list(squared)) # Output: [1, 4, 9, 16]

26
New cards

Defining a Function

def some_function():

statement1

statement2

# More statements as needed

27
New cards

calling or evoking a functions

some_function()

28
New cards

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)

29
New cards

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)

30
New cards

pass by value

def some_function(a):

a = a + 1

print(a)

b = 12

some_function(b)

print(b)

13

12

31
New cards

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

32
New cards

global

?

33
New cards

Return Values

def add(a, b):

return a + b # returns the sum of a and b

result = add(10, 11)

print(result) # Output: 21

34
New cards

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

35
New cards

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)))

36
New cards

International Space Station

  • first component was launched in 1998

  • largest man made object at orbit

  • can be seen with naked eye.

37
New cards

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']

38
New cards

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]