CMPT165-Strings.docx

30 views4 pages

For unlimited access to Class Notes, a Class+ subscription is required.

Strings
•Strings are variables used to store characters (letters, digits, punctuation, spaces)
•When writing the value of a string, you use quotation marks:
E.g. s = "tofurkey"
•Quotation marks indicate where a string begins and ends
•So, what if you want to put quotation marks in a string?
Escape Characters
•In order to do that you need to type a slash before the quotation mark (\")
E.g. print "they said \"hi\" to him"
Program output: they said "hi" to him
•A slash (\) in a string is always the start of a special character (called an escape character)
\n is a newline character
-Everything after it will appear on the next line down
E.g. print "You'll need:\n-Chloroform\n-Duct tape"
Output:
You'll need:
-Chloroform
-Duct tape
\t is a tab character (an indentation, eight spaces wide)
E.g. print "You'll need:\n\tChloroform\n\tDuct tape"
Output:
You'll need:
Chloroform
Duct tape
\\ is an actual slash character
E.g. print "The file's at: C:\\Medicine\\Fungicides"
Output: The file's at: C:\Medicine\Fungicides
•Note that to use escape characters, they must always appear in a string that is, inside
quotation marks
E.g. print \n #ERROR
print "\n" #correct
•Say you need to type a string that is too long to fit in the window
-That is, you have to scroll horizontally to see the whole string
•To avoid having to scroll back and forth, you can break up long strings into several smaller
strings, then join them together with the + operator
•Also, to let Python know that the string continues on the next line down, you need to use a
backslash (\) at the end of the line•Example:
E.g. print "A few of my favourite things:" + \
"\n\tWarm woolen mittens" + \
"\n\tBright copper kettles" + \
"\n\tBrown paper packages tied up " + \
"with string"
Unlock document

This preview shows page 1 of the document.
Unlock all 4 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$10 USD/m
Billed $120 USD annually
Homework Help
Class Notes
Textbook Notes
40 Verified Answers
Study Guides
1 Booster Class
Class+
$8 USD/m
Billed $96 USD annually
Homework Help
Class Notes
Textbook Notes
30 Verified Answers
Study Guides
1 Booster Class