Editing
This commit is contained in:
@@ -1,5 +1,9 @@
|
||||
[Contents](../Contents) \| [Previous (1.2 A First Program)](02_Hello_world) \| [Next (1.4 Strings)](04_Strings)
|
||||
|
||||
# 1.3 Numbers
|
||||
|
||||
This section discusses mathematical calculations.
|
||||
|
||||
### Types of Numbers
|
||||
|
||||
Python has 4 types of numbers:
|
||||
@@ -27,7 +31,7 @@ if d == 0:
|
||||
print('d is False')
|
||||
```
|
||||
|
||||
*Don't write code like that. It would be odd.*
|
||||
*But, don't write code like that. It would be odd.*
|
||||
|
||||
### Integers (int)
|
||||
|
||||
@@ -47,9 +51,9 @@ Common operations:
|
||||
x + y Add
|
||||
x - y Subtract
|
||||
x * y Multiply
|
||||
x / y Divide
|
||||
x // y Floor Divide
|
||||
x % y Modulo
|
||||
x / y Divide (produces a float)
|
||||
x // y Floor Divide (produces an integer)
|
||||
x % y Modulo (remainder)
|
||||
x ** y Power
|
||||
x << n Bit shift left
|
||||
x >> n Bit shift right
|
||||
@@ -165,12 +169,18 @@ Try it out.
|
||||
|
||||
## Exercises
|
||||
|
||||
Reminder: These exercises assume you are working in the `practical-python/Work` directory. Look
|
||||
for the file `mortgage.py`.
|
||||
|
||||
### Exercise 1.7: Dave's mortgage
|
||||
|
||||
Dave has decided to take out a 30-year fixed rate mortgage of $500,000 with Guido’s Mortgage, Stock Investment, and Bitcoin trading corporation.
|
||||
The interest rate is 5% and the monthly payment is $2684.11.
|
||||
Dave has decided to take out a 30-year fixed rate mortgage of $500,000
|
||||
with Guido’s Mortgage, Stock Investment, and Bitcoin trading
|
||||
corporation. The interest rate is 5% and the monthly payment is
|
||||
$2684.11.
|
||||
|
||||
Here is a program that calculates the total amount that Dave will have to pay over the life of the mortgage:
|
||||
Here is a program that calculates the total amount that Dave will have
|
||||
to pay over the life of the mortgage:
|
||||
|
||||
```python
|
||||
# mortgage.py
|
||||
@@ -238,7 +248,7 @@ While you’re at it, fix the program to correct the for overpayment that occurs
|
||||
|
||||
`int()` and `float()` can be used to convert numbers. For example,
|
||||
|
||||
```pycon
|
||||
```python
|
||||
>>> int("123")
|
||||
123
|
||||
>>> float("1.23")
|
||||
@@ -248,7 +258,7 @@ While you’re at it, fix the program to correct the for overpayment that occurs
|
||||
|
||||
With that in mind, can you explain this behavior?
|
||||
|
||||
```pycon
|
||||
```python
|
||||
>>> bool("False")
|
||||
True
|
||||
>>>
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
[Contents](../Contents) \| [Previous (1.3 Numbers)](03_Numbers) \| [Next (1.5 Lists)](05_Lists)
|
||||
|
||||
# 1.4 Strings
|
||||
|
||||
### Representing Text
|
||||
This section introduces way to work with text.
|
||||
|
||||
String are text literals written in programs with quotes.
|
||||
### Representing Literal Text
|
||||
|
||||
String literals are written in programs with quotes.
|
||||
|
||||
```python
|
||||
# Single quote
|
||||
@@ -20,12 +24,17 @@ look into my eyes, you're under.
|
||||
'''
|
||||
```
|
||||
|
||||
Triple quotes capture all text enclosed in multiple lines.
|
||||
Normally strings may only span a single line. Triple quotes capture all text enclosed across multiple lines
|
||||
including all formatting.
|
||||
|
||||
There is no difference between using single (') versus double (")
|
||||
quotes. The same type of quote used to start a string must be used to
|
||||
terminate it.
|
||||
|
||||
### String escape codes
|
||||
|
||||
Escape codes are used to represent control characters and characters that can't be easily typed
|
||||
at the keyboard. Here are some common escape codes:
|
||||
directly at the keyboard. Here are some common escape codes:
|
||||
|
||||
```
|
||||
'\n' Line feed
|
||||
@@ -38,8 +47,8 @@ at the keyboard. Here are some common escape codes:
|
||||
|
||||
### String Representation
|
||||
|
||||
The characters in a string are Unicode and represent a so-called "code-point". You can
|
||||
specify an exact code-point using the following escape sequences:
|
||||
Each character in a string is stored internally as a so-called Unicode "code-point" which is
|
||||
an integer. You can specify an exact code-point value using the following escape sequences:
|
||||
|
||||
```python
|
||||
a = '\xf1' # a = 'ñ'
|
||||
@@ -54,6 +63,7 @@ available character codes.
|
||||
### String Indexing
|
||||
|
||||
Strings work like an array for accessing individual characters. You use an integer index, starting at 0.
|
||||
Negative indices specify a position relative to the end of the string.
|
||||
|
||||
```python
|
||||
a = 'Hello world'
|
||||
@@ -62,7 +72,7 @@ c = a[4] # 'o'
|
||||
d = a[-1] # 'd' (end of string)
|
||||
```
|
||||
|
||||
You can also slice or select substrings with `:`.
|
||||
You can also slice or select substrings specifying a range of indices with `:`.
|
||||
|
||||
```python
|
||||
d = a[:5] # 'Hello'
|
||||
@@ -71,6 +81,8 @@ f = a[3:8] # 'lowo'
|
||||
g = a[-5:] # 'world'
|
||||
```
|
||||
|
||||
The character at the ending index is not included. Missing indices assume the beginning or ending of the string.
|
||||
|
||||
### String operations
|
||||
|
||||
Concatenation, length, membership and replication.
|
||||
@@ -161,7 +173,8 @@ TypeError: 'str' object does not support item assignment
|
||||
|
||||
### String Conversions
|
||||
|
||||
Use `str()` to convert any value to a string suitable for printing.
|
||||
Use `str()` to convert any value to a string. The result is a string holding the
|
||||
same text that would have been produced by the `print()` statement.
|
||||
|
||||
```python
|
||||
>>> x = 42
|
||||
@@ -172,7 +185,7 @@ Use `str()` to convert any value to a string suitable for printing.
|
||||
|
||||
### Byte Strings
|
||||
|
||||
A string of 8-bit bytes, commonly encountered with low-level I/O.
|
||||
A string of 8-bit bytes, commonly encountered with low-level I/O, is written as follows:
|
||||
|
||||
```python
|
||||
data = b'Hello World\r\n'
|
||||
@@ -201,9 +214,13 @@ text = data.decode('utf-8') # bytes -> text
|
||||
data = text.encode('utf-8') # text -> bytes
|
||||
```
|
||||
|
||||
The `'utf-8'` argument specifies a character encoding. Other common
|
||||
values include `'ascii'` and `'latin1'`.
|
||||
|
||||
### Raw Strings
|
||||
|
||||
Raw strings are string literals with an uninterpreted backslash. They specified by prefixing the initial quote with a lowercase "r".
|
||||
Raw strings are string literals with an uninterpreted backslash. They
|
||||
are specified by prefixing the initial quote with a lowercase "r".
|
||||
|
||||
```python
|
||||
>>> rs = r'c:\newdata\test' # Raw (uninterpreted backslash)
|
||||
@@ -237,9 +254,9 @@ is covered later.
|
||||
|
||||
## Exercises
|
||||
|
||||
In these exercises, you experiment with operations on Python's string type.
|
||||
You should do this at the Python interactive prompt where you can easily see the results.
|
||||
Important note:
|
||||
In these exercises, you'll experiment with operations on Python's
|
||||
string type. You should do this at the Python interactive prompt
|
||||
where you can easily see the results. Important note:
|
||||
|
||||
> In exercises where you are supposed to interact with the interpreter,
|
||||
> `>>>` is the interpreter prompt that you get when Python wants
|
||||
@@ -250,7 +267,7 @@ Important note:
|
||||
|
||||
Start by defining a string containing a series of stock ticker symbols like this:
|
||||
|
||||
```pycon
|
||||
```python
|
||||
>>> symbols = 'AAPL,IBM,MSFT,YHOO,SCO'
|
||||
>>>
|
||||
```
|
||||
@@ -259,7 +276,7 @@ Start by defining a string containing a series of stock ticker symbols like this
|
||||
|
||||
Strings are arrays of characters. Try extracting a few characters:
|
||||
|
||||
```pycon
|
||||
```python
|
||||
>>> symbols[0]
|
||||
?
|
||||
>>> symbols[1]
|
||||
@@ -273,8 +290,6 @@ Strings are arrays of characters. Try extracting a few characters:
|
||||
>>>
|
||||
```
|
||||
|
||||
### Exercise 1.14: Strings as read-only objects
|
||||
|
||||
In Python, strings are read-only.
|
||||
|
||||
Verify this by trying to change the first character of `symbols` to a lower-case 'a'.
|
||||
@@ -287,7 +302,7 @@ TypeError: 'str' object does not support item assignment
|
||||
>>>
|
||||
```
|
||||
|
||||
### Exercise 1.15: String concatenation
|
||||
### Exercise 1.14: String concatenation
|
||||
|
||||
Although string data is read-only, you can always reassign a variable
|
||||
to a newly created string.
|
||||
@@ -295,14 +310,21 @@ to a newly created string.
|
||||
Try the following statement which concatenates a new symbol "GOOG" to
|
||||
the end of `symbols`:
|
||||
|
||||
```pycon
|
||||
```python
|
||||
>>> symbols = symbols + 'GOOG'
|
||||
>>> symbols
|
||||
'AAPL,IBM,MSFT,YHOO,SCOGOOG'
|
||||
>>>
|
||||
```
|
||||
|
||||
Oops! That's not what you wanted. Fix it so that the `symbols` variable holds the value `'HPQ,AAPL,IBM,MSFT,YHOO,SCO,GOOG'`.
|
||||
Oops! That's not what you wanted. Fix it so that the `symbols` variable holds the value `'AAPL,IBM,MSFT,YHOO,SCO,GOOG'`.
|
||||
|
||||
```python
|
||||
>>> symbols = ?
|
||||
>>> symbols
|
||||
'AAPL,IBM,MSFT,YHOO,SCO,GOOG'
|
||||
>>>
|
||||
```
|
||||
|
||||
In these examples, it might look like the original string is being
|
||||
modified, in an apparent violation of strings being read only. Not
|
||||
@@ -311,12 +333,12 @@ time. When the variable name `symbols` is reassigned, it points to the
|
||||
newly created string. Afterwards, the old string is destroyed since
|
||||
it's not being used anymore.
|
||||
|
||||
### Exercise 1.16: Membership testing (substring testing)
|
||||
### Exercise 1.15: Membership testing (substring testing)
|
||||
|
||||
Experiment with the `in` operator to check for substrings. At the
|
||||
interactive prompt, try these operations:
|
||||
|
||||
```pycon
|
||||
```python
|
||||
>>> 'IBM' in symbols
|
||||
?
|
||||
>>> 'AA' in symbols
|
||||
@@ -326,13 +348,13 @@ True
|
||||
>>>
|
||||
```
|
||||
|
||||
*Why did the check for "AA" return `True`?*
|
||||
*Why did the check for `'AA'` return `True`?*
|
||||
|
||||
### Exercise 1.17: String Methods
|
||||
### Exercise 1.16: String Methods
|
||||
|
||||
At the Python interactive prompt, try experimenting with some of the string methods.
|
||||
|
||||
```pycon
|
||||
```python
|
||||
>>> symbols.lower()
|
||||
?
|
||||
>>> symbols
|
||||
@@ -342,14 +364,14 @@ At the Python interactive prompt, try experimenting with some of the string meth
|
||||
|
||||
Remember, strings are always read-only. If you want to save the result of an operation, you need to place it in a variable:
|
||||
|
||||
```pycon
|
||||
```python
|
||||
>>> lowersyms = symbols.lower()
|
||||
>>>
|
||||
```
|
||||
|
||||
Try some more operations:
|
||||
|
||||
```pycon
|
||||
```python
|
||||
>>> symbols.find('MSFT')
|
||||
?
|
||||
>>> symbols[13:17]
|
||||
@@ -364,14 +386,14 @@ Try some more operations:
|
||||
>>>
|
||||
```
|
||||
|
||||
### Exercise 1.18: f-strings
|
||||
### Exercise 1.17: f-strings
|
||||
|
||||
Sometimes you want to create a string and embed the values of
|
||||
variables into it.
|
||||
|
||||
To do that, use an f-string. For example:
|
||||
|
||||
```pycon
|
||||
```python
|
||||
>>> name = 'IBM'
|
||||
>>> shares = 100
|
||||
>>> price = 91.1
|
||||
@@ -383,6 +405,31 @@ To do that, use an f-string. For example:
|
||||
Modify the `mortgage.py` program from [Exercise 1.10](03_Numbers) to create its output using f-strings.
|
||||
Try to make it so that output is nicely aligned.
|
||||
|
||||
|
||||
### Exercise 1.18: Regular Expressions
|
||||
|
||||
One limitation of the basic string operations is that they don't
|
||||
support any kind of advanced pattern matching. For that, you
|
||||
need to turn to Python's `re` module and regular expressions.
|
||||
Regular expression handling is a big topic, but here is a short
|
||||
example:
|
||||
|
||||
```python
|
||||
>>> text = 'Today is 3/27/2018. Tomorrow is 3/28/2018.'
|
||||
>>> # Find all occurrences of a date
|
||||
>>> import re
|
||||
>>> re.findall(r'\d+/\d+/\d+', text)
|
||||
['3/27/2018', '3/28/2018']
|
||||
>>> # Replace all occurrences of a date with replacement text
|
||||
>>> re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text)
|
||||
'Today is 2018-3-27. Tomorrow is 2018-3-28.'
|
||||
>>>
|
||||
```
|
||||
|
||||
For more information about the `re` module, see the official documentation at
|
||||
[https://docs.python.org/library/re.html](https://docs.python.org/3/library/re.html).
|
||||
|
||||
|
||||
### Commentary
|
||||
|
||||
As you start to experiment with the interpreter, you often want to
|
||||
|
||||
Reference in New Issue
Block a user