Section 07: Strings Flashcards

Lesson 08 and 09

1
Q

Overview of strings:

A
  • Strings ordered collection of characters
  • Each has an index, starting at 0
  • Characters of a string can be retrieved using their index (or negative indices)
  • Strings are immutable
  • To create a new string, use slicing and string addition
  • Strings have methods, including lower, upper, replace, split, count, find
  • Comparing strings use == operator

Immutable sequence of Characters

Operators: + and *

  • + for concatenation between two strings $s$ and $t$
  • * between str(x) and int(x).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What operators work on strings?

A

Operators: + and *

  • + for concatenation between two strings $s$ and $t$
  • * between str(x) and `int(x)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

String: Length

A
  • Let s be a variable referencing a value of type string (str).

Useful function: len(s)

Takes a string s as input, and returns num of characters in s.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Strings in a sequence

A
  • String ordered collection of characters
  • Each has an index (starting at zero)First characters: index 0 and last has index n-1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Accessing Characters in a String:

A

Characters of a string can be retrieved using their index

  • Can use negative indices to access characters → count backwards[-1] refers to the last character in a string

IndexError program stops if index DNE ⇒ error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Errors

IndexError

A

IndexError program stops if index DNE ⇒ error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Valid range for characters in a string:

A

[-len(s), len(s)-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Strings

How are strings immutable?

A

Strings are immutable:

String objects are immutable. Immutable simply meansunmodifiable or unchangeable. Once String object is created its data or state can’t be changed but a new String object is created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Slicing

What is slicing?

A

from start until index 3

  • Pieces off strings can be retrieved using a special form of indexing called “slicing
  • A start and end index is needed
    • If start omitted: slice begin start sentence
    • If end omitted: slipe continue till end

`»> fruit = ‘banana’

> > > print(fruit[:3])
ban

> > > print(fruit[3:])
ana`

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Slicing Strings

Step Value:

A

Step Value: thrid num when slicing → indicates how many indices to skip between characters

Same concept as range(start, end, step)

> > > s = ‘Hello world’
print(s[0:5:2])
Hlo

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Slicing Strings

Negative Skip Value

A

Negative Skip Value: decrease by the given amount

> > > s = ‘Hello world’
print(s[::-1])
dlrow olleH

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are immutable objects?

A
  • Strings immutable objects

  • Cannot use square brackets to modify a character in string
    »> s = ‘cats’
    »> s[0] = ‘r’

TypeError

Working Solution:

python
s = 'cats' 
s = 'r' + s[1:] 

*Re-creating a new variable s and not changing the old one *

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to create a new string?

A

To create a new string: use slicing and string addition

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Methods

s.lower()

A

(1) s.lower()

Returns a copy of s, all lower-case

> > > s = “HELLO”
s.lower()
‘hello’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

String Methods

(2) s.upper()

A

(2) s.upper()
Returns a copy of s, but all upper case

> > > s = ‘small’
s.upper()
‘SMALL’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

String Methods

(3) s.replace(old, new)

A

(3) s.replace(old, new)
string with all occurrences of substring old replaced by new

> > > s = ‘hello’
s.replace(‘l’, ‘y’)
‘heYYo’

17
Q

String Methods

(4) s.split(separator)

A

(4) s.split(separator)
Output: list of substrings in s separated by separator

> > > s = “Hi, I am a string”
s.split(‘,’)
[‘Hi’, ‘ I am a string’]

18
Q

String Methods

(5) s.count(c)

A

(5) s.count(c)

Returns num of non-overlapping occurences of c in s

> > > s = ‘Hello world’
s.count(‘l’)
3

19
Q

String Methods

(6) s.find(c)

A

(6) s.find(c)

Takes a substring as input and returns index where the first occurence of the substring s begins

If not a substring, then -1 returned

index of first occurence of substring c in s

> > > s = ‘Hello world’
s.find(‘ld’)
9

20
Q

String Methods

(7) s.find(c, start, end)

A

(7) s.find(c, start, end)

index of first occurrence of substring c in s between indices start and end (inclusive)

> > > s = ‘Hello world’
s.find(‘d’, 0, 5)
-1

21
Q

Compare strings

A

Comparing strings use the == operator

true if strings equal, false if strings not equal

  • For characters, ASCII codes assigns each character a number
  • D < c < d

> > > s = ‘Hello world’
s == ‘Hello world’
True

22
Q

The in opertor

A
  • In Python, in is a keyword
  • The in and not in operators test for membership

Use to test if one string is a substring of another

True or False

> > > ‘d’ in ‘Hello world’
True

23
Q

Random

uniform() method

A

uniform() method in Python isused to return a random floating-point number that is greater than or equal to the specified low boundary, and less than or equal to the specified high boundary

Generate a (pseudo)-random number
Using random module:

import random #Top of file -> Provides different functions

24
Q

Random

What is the random import

A

Using random module:

```python
import random #Top of file -> Provides different functions
~~~

  1. random(): Returns random float value between 0.0 (inclusive) and 1.0 (exclusive)
  2. randint(x, y): Retruns random int value between x and y, both included
25
Q

Random

Random Seed

A

Random Seed:

  • Number generation not truley random → determined by initial value = **seed**
  • If no seed specified: use generate the number is the current system time → then always differentFix seed function: random.seed()
26
Q

Traversing a String

How to traverse a string:

A

Process of going through a string one character at a time
Error type: IndexError

1. While loop, 2. for loop w index, 3. for loop w characters

27
Q

Traversing a string

(1) Using a while loop

A

```python
fruit = ‘banana’
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
~~~

28
Q

Traversing a String

(2) Using a for loop through the indices of a string

A

```python
s = ‘banana’
for i in range(len(s)):
print(s[i])
~~~

```python
s = ‘apple’
for i in range(len(s) -1):
print(s[i], end=” “)
#Output: a p p l
~~~

29
Q

Traversing a String

(3) Using a for loop through the characters of a string

A

```python
fruit = ‘banana’
for letter in fruit:
print(letter) #Output: print letters on separate lines
or …
print(letter, end = “ “) #Output: prints lets on the same line
~~~

30
Q

Traversal with a for loop comparison

A

For for loops:

  1. Loop by index: for i in range (len(s))
    • Gives access to index
  2. Loop by value for char in s
    • Saves from possible off-by-one (IndexError) Error