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
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)。
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
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.