From last time: How can you get a list of variables?
Python provides a couple of functions to tell you about the variables (and functions/methods, modules, and classes - more on these later) currently in existence:
Last class, we saw the assignment operator (=
). There are actually many assignment operators. To create them, basically combine the arithmetic operator with the assignment operator. For example:
The above examples are short-hand for:
These combined arithmetic/assignment operators are for the convenience of programmers. It's ok if you don't use them much. They are mostly used to increment/decrement variables (usually by one).
The Python interpreter will display the result of a statement. That's nice for now, but it'd be nice to get fancier output. Plus, as we get to bigger programs, we won't be using the interpreter, so it'd be good to know how to display output to the user.
Python has a function called print
that we can use to display output. I'm introducing it now so we can see what strings of text actually look like. Since we haven't seen strings yet, let's just see how to use print with numbers, but it'll be the same with strings.
print
takes a comma-delimited list of things (called "arguments") to print, e.g.:
Notice that each argument in the print function is separated by a comma. Notice that when they're printed out, the comma doesn't show up. Instead, there's a space there. That space isn't because there was a space in the print function:
You can put as many arguments in a print function as you want (and they can all be different types):
What do you think happens if you put nothing in the parentheses? In other words, what does this do: print()
In programming, "string" means "collection of characters" (or basically "text"). To create a string in Python, surround your text with quotes. It doesn't matter if you use single quotes (') or double quotes ("), as long as you're consistent.
What if you want your string to contain a quote? Just use the other kind of quote.
What if you want your string to contain both kinds of quotes? You have two options: escape sequences or multi-line strings.
Certain characters are hard to represent in a string, but you may want them in a string. One way to get them into a string is with an escape sequence. Below are the escape sequences Python supports:
Escape Sequence | Represents | Description |
---|---|---|
\n | newline | Advances the cursor to the next line |
\r | carriage return | Causes the cursor to go to the beginning of the current line, not the next line |
\b | backspace | Causes the cursor to back up, or move left, one position |
\t | tab | Causes the cursor to skip over to the next tab stop |
\' | single quote | Causes a single quote to be printed |
\" | double quote | Causes a double quote to be printed |
\\ | backslash | Causes a backslash to be printed |
Here's an example of using some of them:
Notice that using the print function displays the string correctly. It also no longer displays the outputted string surrounded by quotes.
If you want a string to span multiple lines, using '\n' is good, but sometimes it makes reading your code harder. Instead, you can create multi-line strings. To do that, surround your string with three quotes on either side instead of just one quote:
Notice that the interpreter puts all of it into one string and escapes all of the characters that need to be escaped. But, it didn't display nicely. Again, to get it to display nicely, we really should be using the print function:
Assigning strings into a variable is the same way as with numbers.
Notice that there is no space at the end of msg but there is a space between the end of msg and the value stored in x.
Just like with numbers, strings have a lot of operations you can do with them.
Operation | Description | Example |
---|---|---|
Concatenation | Combine two strings into one (new) string |
>>> str2 = "that was in two parts." >>> str3 = str1 + str2 >>> print(str3) Here is a string that was in two parts. |
Combined Concatenation and Assignment |
Combine two strings into one (new) string |
>>> str1 += "that was in two parts." >>> print(str1) Here is a string that was in two parts. |
Length | The number of characters in the string. Returns an int. |
>>> len(str1) 21 |
Convert to Lowercase | Return a new string where all characters in the string are lowercase. |
>>> print(str1.lower()) this string is short. |
Convert to Uppercase | Return a new string where all characters in the string are uppercase. |
>>> uppercase_str1 = str1.upper() THIS STRING IS SHORT. |
Capitalize | Return a new string. If the first character of the existing string is a letter, then it is capitalized, otherwise there is no change to the string. |
>>> print(str1.capitalize()) This string is short. |
Count | Count the number of times a substring appears in the string. |
>>> count_s = str1.count('s') >>> print('In the string "'+str1+'", the letter "s" appears', count_s, 'times.') In the string "This string is short.", the letter "s" appears 4 times. >>> >>> count_is = str1.count('is') >>> print('In the string "'+str1+'", the substring "is" appears', count_is, 'times.') In the string "This string is short.", the substring "is" appears 2 times. |
Find | Find the first occurrence of the specified substring and return it starting position in the string. Note: The positions start at 0. If the substring is not found, it returns -1. |
>>> pos_is = str1.find('is') >>> print("The first occurrence of 'is' is at ", pos_is) The first occurrence of 'is' is at 2 |
Index | Just like Find, but raises a ValueError exception if the substring is not found. |
>>> pos_zzz = str1.index('zzz') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found |
In | Just tells you whether or not a substring is in the string. Doesn't tell you where it is or how many there are. |
>>> 'is' in str1 True >>> 'zzz' in str1 False |
Substring | Get just part of an existing string. You specify the starting position and the position to go up to, but not include. Note: In Python (and almost every other language), you start counting at 0. |
>>> str1[0:6] 'This s' >>> str1[5:10] 'strin' >>> str1[str1.find('sh'):length(str1)] 'short.' |
Notice that some of these are functions belonging to a string object (e.g. find
and index
), others are functions that take a string object (len
), some have a math-like operation (+
), and others use a Python keyword (in
). While these may seem inconsistent now, it makes sense in the larger context of the Python language. There are many different data structures that have a length or can contain things, so it makes sense to have a uniform way to get the length of something or to see if one thing is contained in another thing.
There are many other string operations you can perform. You can find a list in the Python documentation. We will talk about some of these later in the semester.
What do you think happens with:
Converting between strings and numbers is fairly easy. To convert a string into a number, use the int
or float
functions we saw last time. To convert a number into a string, use the str
function. If you want to combine a string and a number, you'll first need to convert a number into a string. The simplest way is to use the str
function:
There are a lot of options when it comes to formatting numbers in Python (Format specification). Today, we will cover only the very basics of formatting.
Python provides a function called format
that formats something according to a specified format and returns a string. The formatting is similar to the %-notation you may be familiar with from other languages.
If you don't want a string back, but just want a number rounded to a certain number of decimal places, use the round
function:
Python offers a lot of help to programmers, if you know where to look. The documentation online is great, but sometimes you won't have access to it or you're using a module that doesn't have documentation available. Python still has some help for you!
The help function takes a function, module, or class and offers some documentation on it. It will describe how to use the thing and what is needed to use it. However, this requires that the writer of the function, module, or class also wrote documentation. If they didn't, this won't offer much help.
The dir function takes any object in Python (function, module, class, variable, etc) and tells you all of the functions and variables that it has. It doesn't tell you what they do, but it's at least something.
Notice that x has all of the string functions mentioned above.
<< Previous Notes | Next Notes >> |