码迷,mamicode.com
首页 > 编程语言 > 详细

Python(2)-第二天

时间:2016-06-07 22:04:02      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:

除法

>>> 8 / 5 
1
>>> 8 / 5.0
1.6
>>> 8.0 / 5
1.6
>>> 8 // 5.0
1.0

余数

>>> 8 % 5 
2

**运算符

>>> 5 ** 2 
25

=运算符

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

_变量,表示最近一次表达式的值

>>> _ 
900

字符串输出

>>> ‘spam eggs‘
‘spam eggs‘
>>> "span eggs"
‘spam eggs‘
>>> ‘"Yes," he said.‘
‘"Yes," he said.‘

转义

说明:输出的字符串会用引号引起来,特殊字符会用反斜杠转义。

虽然可能和输入看上去不太一样(外围的引号会改变),但是两个字符串是相等的。

如果你前面带有\的字符被当作特殊字符,你可以使用原始字符串,方法是在第一个引号前面加上一个r:

>>>  ‘doesn\‘t‘
"doesn‘t"
>>> "\"Yes,\" he said."
‘"Yes," he said.‘
>>> r‘doesn\‘t‘
"doesn\‘t" 
>>> 8 // 5.0
1.0

字符串跨多行(""")

>>> print """Usage: thingy [OPTIONS]
     -h                        
     -H hostname               
"""
Usage: thingy [OPTIONS]
     -h                        
     -H hostname

字符串连接

>>> ‘Py‘ + ‘thon‘
‘Python‘
>>> ‘Py‘ ‘thon‘
‘Python‘
>>> ‘Py‘ * 3
‘PyPyPy‘

字符串的索引

>>> word = ‘Python‘
>>> word[0]
‘P‘
>>> word[5]
‘n‘

索引为负数时,此时从右侧开始计数(因为-0和0是一样的,索引索引从-1开始)

>>> word = ‘Python‘
>>> word[-1]
‘n‘
>>> word[-6]
‘P‘

切片(截取字符串)

>>> word = ‘Python‘
>>> word[0:2]
‘Py‘
>>> word[2:5]
‘tho‘

包含起始的字符,不包含末尾的字符。这使得s[:i] + s[i:]永远等于s

>>> word = ‘Python‘
>>> word[:2] + word[2:]
‘Python‘

切片的索引有非常有用的默认值;省略的第一个索引默认为零,省略的第二个索引默认为切片的字符串的大小

>>> word = ‘Python‘
>>> word[:2]
‘Py‘
>>> word[4:]
‘on‘
>>> word[-2:]
‘on‘

当用于切片时,超出范围的切片索引会被优雅地处理:

>>> word = ‘Python‘
>>> word[4:42]
‘on‘
>>> word[42:]
‘‘

内置函数len()

>>> word = ‘Python‘
>>> len(word)
6

Unicode字符串

创建Unicode字符串与创建普通字符串一样简单,u表示内置函数unicode()

>>> u‘Hello World !‘
u‘Hello World !‘

如果字符串中包含特殊字符,可以使用Unicode转义编码

>>> u‘Hello\u0020World !‘
u‘Hello World !‘

Unicode字符串的raw模式

>>> ur‘Hello\\u0020World !‘
u‘Hello\\\\u0020World !‘

列表

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

和字符串(以及其他所有内置的序列类型)一样,列表可以索引和切片

>>> squares = [1, 4, 9, 16, 25]
>>> squares[0] 
1
>>> squares[-1] 
25
>>> squares[-3:] 
[9, 16, 25]

列表也支持连接

>>> squares = [1, 4, 9, 16, 25]
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

列表是可变的(字符串是不可变的)

>>> squares = [1, 4, 9, 16, 25]
>>> cubes[3] = 33
>>> cubes
[1, 4, 9, 33, 25]

append()方法

>>> cubes= [1, 4, 9]
>>> cubes.append(16)
>>> cubes
[1, 4, 9, 16]

给切片赋值,此操作甚至可以改变列表的大小或者清空它

>>> letters = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘]
>>> letters[2:5] = [‘C‘, ‘D‘, ‘E‘]
>>> letters
[‘a‘, ‘b‘, ‘C‘, ‘D‘, ‘E‘, ‘f‘, ‘g‘]
>>> letters[2:5] = []
>>> letters
[‘a‘, ‘b‘, ‘f‘, ‘g‘]
>>> letters
[‘a‘, ‘b‘, ‘C‘, ‘D‘, ‘E‘, ‘f‘, ‘g‘]

len函数

>>> letters = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘]
>>> len(letters)
4

嵌套列表

>>> a = [‘a‘, ‘b‘, ‘c‘]
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[[‘a‘, ‘b‘, ‘c‘], [1, 2, 3]]
>>> x[0]
[‘a‘, ‘b‘, ‘c‘]
>>> x[0][1]
‘b‘

Python(2)-第二天

标签:

原文地址:http://www.cnblogs.com/2star/p/5568289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!