非正式介紹Python(一)

3.1. Using Python as a Calculator

Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>>. (It shouldn’t take long.)html

咱們先試着寫些簡單的Python命令語句,打開Python解釋器(IDLE(後面出現解釋器通常指IDLE)),等待>>>提示符的出現。python

3.1.1. Numbers

The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses (()) can be used for grouping. For example:express

 解釋器能夠看成簡單的計算器:你能夠輸入輸入表達式,它會直接顯示結果。表達式的語法是很是明瞭的:+,-,* / 和其餘語言(例如:Pascal 和 C)是相同的做用。例如:ide

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6

 The integer numbers (e.g. 2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have type float. We will see more about numeric types later in the tutorial.函數

整數(例如:2,4,20)類型爲int,有小數點部分(例如:5.0,1.6)則類型爲float。咱們將會看到更多整數相關類型ui

Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you can use the // operator; to calculate the remainder you can use %:this

除法(/)老是返回float類型,想要獲得int型結果,請用 // 運算符,要計算餘數,則使用%:spa

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17

 

 With Python, it is possible to use the ** operator to calculate powers code

在Python中,咱們能夠使用**運算符進行乘方運算:orm

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

 

 The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:

 等號=用做賦值運行,賦值結束後不會直接顯示結果,須要再按一下回車。

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

 

 If a variable is not 「defined」 (assigned a value), trying to use it will give you an error:

若是一個變量未定義,當使用時則會報錯:

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

 There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:

當表達式中有整型和浮點類型時,則解釋器會將整型轉換爲浮點類型:

>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5

 

 In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:

在Python交互模式下,最後一個表達式的結果會自動複製給 _ 變量,這意味着你把Python看成一個計算器使用時,很容易用最後的計算結果進行下一步計算,例如:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

 

 This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

咱們應該把 _ 變量看成只讀的,不要顯示的去給它賦值。若是你建立一個本地變量名字和Python內置變量同樣,這是一個很差的行爲!

In addition to int and float, Python supports other types of numbers, such as Decimal and Fraction. Python also has built-in support for complex numbers, and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j).

除了int 和 float類型,Python還支持其餘整數類型,例如Decimal和Fraction類型,Python還有內置的複數類型,使用 j 或 J 後綴表示他的虛數部分(例如: 3 + 5j)。

3.1.2. Strings

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result [2]. \ can be used to escape quotes:

除了數值類型外,Python還能夠用不一樣的方式使用字符串,能夠使用單引號或雙引號將字符串括起來,其結果是相同的。也能夠使用 \ 進行轉義。

'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

 

 In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:

在Python交互式解釋器中,字符串的輸出結果使用引號括起來了,特殊字符則經過\反斜槓進行了轉義。咱們可能發現了他們可能和輸入有點不同(括起來的引號變了),可是他們是相等的。若是字符串包含單引號而且不包含雙引號,則輸出結果用雙引號括起來,不然用單引號括起來。print()函數輸出字符串更具備可讀性,它不會將輸出結果用引號括起來。

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.

 

 If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:

若是你不想使用反斜槓\來轉義特殊字符,那麼你能夠在原始字符串前加 r :

>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\name 

 String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:

字符串常量可用跨越多行,其中一種使用方式是用 """ ... """ 或者 ''' ... '''。若是在第一個三引號後面不加反斜槓\,則字符串以前會自動加一空行。能夠用反斜槓 \ 阻止這種行爲。

 produces the following output (note that the initial newline is not included):

下面是輸出結果(注意,開始一行是沒有空行的):

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

Strings can be concatenated (glued together) with the + operator, and repeated with *:

字符串能夠經過+運算符進行連接,或者經過*進行重複連接:

>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'

Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.

兩個字符串常量則會自動進行鏈接運算:

>>> 'Py' 'thon'
'Python'

This only works with two literals though, not with variables or expressions:

上面的操做僅適用於兩個字符串常量,變量和常量是不能夠鏈接的:

>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  ...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  ...
SyntaxError: invalid syntax

If you want to concatenate variables or a variable and a literal, use +:

若是你想將變量和常量鏈接,則使用+運算符:

>>> prefix + 'thon'
'Python'

This feature is particularly useful when you want to break long strings:

這種特徵特別適用於長字符串的分行書寫:

>>> text = ('Put several strings within parentheses '
            'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:

字符串能夠使用索引操做,第一個字符的索引爲0,Python中沒有單獨的字符類型,一個字符也字符串。

>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'

Indices may also be negative numbers, to start counting from the right:

索引能夠使負數,表示從字符串的右邊開始進行索引:

>>> word[-1]  # last character
'n'
>>> word[-2]  # second-last character
'o'
>>> word[-6]
'P'

Note that since -0 is the same as 0, negative indices start from -1.

注意,由於 -0 和 0 是一致的,所以負數索引是從-1開始。

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:

除了索引以外,字符串還支持切片操做。索引用來表示單個字符,切片容許你包含子串:

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'

Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s:

注意,切片遵照前閉後開原則。s[:i] + s[i:] 老是等於 s:

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

切片的前一個索引默認爲0,第二個索引默認爲字符串的長度:

 

>>>>>> word[:2]  # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]  # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'

However, out of range slice indexes are handled gracefully when used for slicing:

若是索引越界,切片操做能夠很優雅的進行處理:

>>> word[4:42]
'on'
>>> word[42:]
''

Python 字符串是不可變量,所以,給某個索引位置進行賦值是不行的:

>>> word[0] = 'J'
  ...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
  ...
TypeError: 'str' object does not support item assignment

The built-in function len() returns the length of a string:

內置函數len()返回字符串的長度:

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

Text Sequence Type — str

Strings are examples of sequence types, and support the common operations supported by such types.

字符串屬於序列類型,序列的常見操做均可以用於字符串。

String MethodsStrings support a large number of methods for basic transformations and searching.

字符串用於大量的方法用於轉換和搜索。

String FormattingInformation about string formatting with str.format() is described here.

字符串格式化

printf-style String FormattingThe old formatting operations invoked when strings and Unicode strings are the left operand of the % operator are described in more detail here.

相關文章
相關標籤/搜索