Section 07: Strings Flashcards
Lesson 08 and 09
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’