Module 8 - Strings Flashcards
How are strings different from integers, floats, and booleans?
A string is a sequence - an ordered collection of other values, where each value is identified by an integer index
How do you access each character in a string?
The bracket operator
How would you access the first letter in banana?
fruit = ‘banana’
letter = fruit[0]
^ selects first character from fruit and assigns it to letter
What is an index?
The expression in brackets
An integer value used to select an item in a sequence, such as a character in a string. In Python indices start from 0
What types of values can you put into a string index?
Value MUST evaluate to an integer, but you can use numbers, operators, and expressions in the brackets: 0 if i=1, can do i+1 2*3 etc..
What is len? What is the syntax for it?
Function that returns the number of characters in a string
size=len(‘fruit’)
print(size)
5
How would you get the last character of a string?
fruit = ‘banana’ #assign value ‘banana’ to var fruit
length = len(fruit) #assign length to var length
last = fruit[length-1] #assign last letter to var last
print(last) #displays ‘a’
remember, b is the zero’th letter!!
you can also use negative indices - fruit[-1] gives you last letter
What does it mean to traverse?
To iterate through the items in a sequence, performing a similar operation on each.
For example, processing a string one character at a time
What is concatenation?
String addition
What is a string slice? What is the syntax?
AKA substring - a segment of a string is called a slice
string [start:end] returns the string from the start (default is 0) up to, but EXCLUDING, the end value
How do you slice from the beginning or to the end?
If you want to slice from the beginning, leave first one blank, [ :3] – it defaults to 0 if blank
If you want to slice to the end, leave last one blank, [3;] – defaults to len(string) if blank
What is the result if the first index is greater than or equal to the second index in a slice? i.e., [3:2] or [3:3]
An empty string
no characters and length 0 but still a string
What happens if you leave both indices empty? i.e., [:]
The entire string is return - not sliced
T or F: Strings are sequences (lists), so many of
the tools that work with sequences work
with strings
True!
What happens if you try to use an index that is out of range for the string?
IndexError exception will occur