Section 07: Strings Flashcards
Lesson 08 and 09 (30 cards)
Overview of strings:
- 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$ -
*
betweenstr(x)
andint(x)
.
What operators work on strings?
Operators: +
and *
-
+
for concatenation between two strings $s$ and $t$ -
*
betweenstr(x)
and `int(x)
String: Length
- 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.
Strings in a sequence
- String ordered collection of characters
- Each has an index (starting at zero)First characters: index 0 and last has index n-1
Accessing Characters in a String:
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
Errors
IndexError
IndexError program stops if index DNE ⇒ error
Valid range for characters in a string:
[-len(s), len(s)-1]
Strings
How are strings immutable?
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.
Slicing
What is slicing?
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`
Slicing Strings
Step Value:
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
Slicing Strings
Negative Skip Value
Negative Skip Value: decrease by the given amount
> > > s = ‘Hello world’
print(s[::-1])
dlrow olleH
What are immutable objects?
- 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 to create a new string?
To create a new string: use slicing and string addition
Methods
s.lower()
(1) s.lower()
Returns a copy of s, all lower-case
> > > s = “HELLO”
s.lower()
‘hello’
String Methods
(2) s.upper()
(2) s.upper()
Returns a copy of s, but all upper case
> > > s = ‘small’
s.upper()
‘SMALL’
String Methods
(3) s.replace(old, new)
(3) s.replace(old, new)
string with all occurrences of substring old
replaced by new
> > > s = ‘hello’
s.replace(‘l’, ‘y’)
‘heYYo’
String Methods
(4) s.split(separator)
(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’]
String Methods
(5) s.count(c)
(5) s.count(c)
Returns num of non-overlapping occurences of c in s
> > > s = ‘Hello world’
s.count(‘l’)
3
String Methods
(6) s.find(c)
(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
String Methods
(7) s.find(c, start, end)
(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
Compare strings
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
The in
opertor
- In Python,
in
is a keyword - The
in
andnot in
operators test for membership
Use to test if one string is a substring of another
True
or False
> > > ‘d’ in ‘Hello world’
True
Random
uniform()
method
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
Random
What is the random import
Using random
module:
```python
import random #Top of file -> Provides different functions
~~~
-
random()
: Returns random float value between 0.0 (inclusive) and 1.0 (exclusive) -
randint(x, y)
: Retruns random int value between x and y, both included