Test Review
Reading Questions
Quiz
String Operators
We’ve already seen strings, they are text inside of quotes
text = "this is a string"
- Now we are learning how to write programs that use and manipulate strings
- One way is with string operators
- Numerical operators are +, -, *, /, etc.
- Comparison operators are >, <, ==, etc.
- Logical operators are and, or, not
- String operators are + and *
The + operator doesn’t add, it joins two strings together into a new string, this is called concatenation
print("hello" + "everybody")
- Note, this is different than using a comma in a print statement in two ways
- First, it doesn’t add the space automatically
Second, it can be used outside of a print statement
greeting = "hello" audience = "everybody" greeting = greeting + " " + audience print(greeting)
- Also note, operands must both be stings
Can also compare whether two strings are equal
name = input("enter name: ") if name == "nobody": print("hello nobody")
Index Operator
- Each character in a string has a unique location
- The location, or index, of a character is the characters distance from the first character
- For example, in the string “hello”, h has the index 0, e has the index 1, etc.
The index operator can be used to copy a character out of a string
text = "hello" first_character = text[0] print(first_character)
Negative indices can be used to access characters from the end
text = "hello" last_character = text[-1] print(last_character)
Indices that are too large or too small will produce an error
text = "hello" nonexistent_character = text[5] # Error print(nonexistent_character)
String Traversal
Use a loop and the index operator to do something for every character in a sting
text = "hello" for i in range(len(text)): print(text[i])
Can even have accumulators with strings
text = "hello" new_text = "" for i in range(len(text) - 1): new_text = text[i] + "-" print(new_text)
Note that the initial value of the accumulator variable is a string with no characters, the empty string