程序员程序员Python 运维

Python笔记3:语法糖

2017-10-31  本文已影响50人  世外大帝

运算

数字运算

>>> 2+2
4

>>> 50-5*6
20

>>> (50-5*6)/4
5.0

>>> 8/5
1.6

>>> 5.0/1.6
3.125

>>> 17//3
5

>>> 17%3
2

# 赋值
>>> width = 20
>>> height = 30
>>> width * height
600

# 阶乘
>>> 2**7
128

>>> 5**2
25

# 默认赋值符
>>> 4*3.5+5-8.5
10.5
>>> _*3
31.5
>>> _+0.123
31.623

# 保留小数点
>>> round(_,2)
31.62

字符串


# 相同引号不转义会报错
>>> 'It's'
  File "<stdin>", line 1
    'It's'
        ^
SyntaxError: invalid syntax


# 转义
>>> 'It\'s'
"It's"

>>> "\"Yes,\" he said."
'"Yes," he said.'


# 不同引号可以直接包含
>>> "It's"
"It's"


# \n是换行符
>>> print('line\nnewline')
line
newline


# 加r 使用原始字符串
>>> print(r'line\nnewline')
line\nnewline


# 换行符
>>> print("""
... hello
... world
... """)

hello
world


# 换行,防止空行
>>> print("""\
... hello
... world
... """)
hello
world


# 字符串 + * 运算
>>> print(3*" hello " + 'world')
 hello  hello  hello world
 
 
 # 字符串自动拼接
 >>> 'python' ' good'
'python good'


字符串索引

>>> content = 'hello world'

# 正索引
>>> content[0]
'h'
>>> content[5]
' '
>>> content[9]
'l'

# 后端索引
>>> content[-1]
'd'
>>> content[-5]
'w'

# 连续索引
# content[包括:不包括] 
>>> content[:5] # 0-5
'hello'
>>> content[4:5] # 4-5
'o'
>>> content[0:] # 0-end
'hello world'

>>> content[-10:] # end-(end-10)
'ello world'

# 长度
>>> len(content)
11

Lists

# 列表不同的项之间用逗号隔开
# 最好后面再加个空格,和下面打印出来的一样
>>> list = [1,2,3,4,5,100]
>>> list
[1, 2, 3, 4, 5, 100]

# 索引,和字符串一样
>>> list[2]
3
>>> list[-2]
5
>>> list[-2:]
[5, 100]
>>> list[:-2]
[1, 2, 3, 4]

# 全部请求
>>> list[:]
[1, 2, 3, 4, 5, 100]

# 连接list
>>> list + [101,102]
[1, 2, 3, 4, 5, 100, 101, 102]

# 可变类型
>>> list[1] = 11
>>> list
[1, 11, 3, 4, 5, 100]

# 追加操作
>>> list.append(103)
>>> list
[1, 11, 3, 4, 5, 100, 103]

# 胡求变
>>> list
[1, 11, 3, 4, 5, 100, 103]
>>> list[1:3] = ['A','b','C']
>>> list
[1, 'A', 'b', 'C', 4, 5, 100, 103]
>>> list[0:2] = []
>>> list
['b', 'C', 4, 5, 100, 103]
>>> list = []
>>> list
[]

# 列表嵌套及运算
>>> a = [2,3,4]
>>> b = [3,4,5]
>>> list = [a,b]
>>> list
[[2, 3, 4], [3, 4, 5]]

>>> list = list + a + b
>>> list
[[2, 3, 4], [3, 4, 5], 2, 3, 4, 3, 4, 5]

>>> list[1]
[3, 4, 5]
>>> list[5]
3
>>> list[0][2]
4

# 斐波那契数列(注意...格式,否则会报错)
>>> a,b = 0,1
>>> while b< 1000:
...     print(b,end=',')
...     a,b = b,a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,>>>
上一篇 下一篇

猜你喜欢

热点阅读