Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Introduction to strings
Basics
We define strings using either single or double quotes csca20 or "csca20" unless it needs to
span more than one line and then we use triple quotes:
>>> This is a sentence
... on several lines
... it is too long
... to fit on one line.
This is a sentence\non several lines\nit is too long\nto fit on one line.
Hold on, well find out what \n stands for shortly!
Q. What do you think the result of csca + 20 is?
A.
Q. What other use does + have?
A.
We say that + is overloaded.
Q. How do you think Python knows what to do?
A.
Q. Why would "csca" + 20 result in an error?
Slicing Strings
Since strings are sequences of characters, we sometimes want to be able to retrieve portions of the
string. To do so, we need to have a way to refer the ith character. By convention, the first character
has position or index 0. Each subsequent character has index one greater.
Here are the ways we can access characters in a string s:
s = "sliceofspam"
s[0]
# Grab a single character. First index is zero.
s[3]
s[-2]
# Negative indexes are for counting from the RHS
s[2:5]
s[3:]
s[:8]
s[:]
#
#
#
#
#
s[3:-2] #
s[-5:] #
s[5:2] #
String Methods
campus.startswith(ut)
You need to know when you are calling a method vs calling a function; the notation is
different. For example:
s = "Hi, CSCA20 students!"
len(s)
# len is a built-in function. s is the argument passed in.
s.len()
# Doesnt work. len is not a string method.
s.lower()
lower(s)
Q. How can we get a list of all string methods with their descriptions?
A.
For the methods listed below, assume that the string we are using is: s = "This is CSC120/A20".
Method
s.lower()
s.replace("20", "48")
s.count("i")
"yabababa daba do!".count("abab")
s.find("is")
s.rfind("is")
s.find("is", 3)
s.find("is", 2)
s.find("the")
Define a new s = "
Method
s.lstrip()
s.rstrip()
s.strip()
Output
quite
open
Output
Explanation
line
Explanation
".
Loops
Sometimes we need to do something with each character in a string. This is called looping or
iterating over the string.
The form for looping through a string:
for char in s:
<do something involving char>
for, in are Python keywords
char is a variable that holds the value of the current character
s is the string (for now)
For example,
def print_vertical(s):
for char in s:
print(char)
Q. Trace the call print vertical("word")
Lets Practice
Escape Sequences
\"
Example
import math
print("pi is %.15f" % (math.pi))
r = 9.625
Write a print statement that calculates the area of a circle of radius r and outputs:
A circle of radius 9.625000 has area 291.0391.
Example
Write a snippet of code to ask for the users name and age and then print:
NAME is YYY years old.
8.1
You may find formatting with the % operator awkward, though it does improve with familiarity.
An alternative is the built-in function format, which we will not cover here.