python 语法笔记(一)

1.输入和输出

当你输入name = input()并按下回车后,Python交互式命令行就在等待你的输入了。这时,你可以输入任意字符,然后按回车后完成输入。

>>> name = input()
alice
print('hello,', name)#打印函数

 

2.数据类型与变量

字符串

如字符串内部既包含'又包含"怎么办?可以用转义字符\来标识,比如:

>>>'I\'m \"OK\"!'
I'm "OK"!

>>> print('I\'m ok.')
I'm ok.
>>> print('I\'m learning\nPython.')
I'm learning
Python.
>>> print('\\\n\\')
\
\

 

如果字符串里面有很多字符都需要转义,就需要加很多\,为了简化,Python还允许用 r''表示''内部的字符串默认不转义:

>>> print('\\\t\\')
\       \
>>> print(r'\\\t\\')
\\\t\\

如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用'''...'''的格式表示多行内容:

>>> print('''alice1
... alice2
... alice3''')
alice1
alice2
alice3

布尔值

 布尔值只有TrueFalse两种值,要么是True,要么是False,在Python中,布尔值,可以直接用TrueFalse表示布尔值(请注意大小写),也可以用andornot运算计算出来

#通过布尔运算计算出来
>>> True
True
>>> False
False
>>> 3 > 2
True
>>> 3 > 5
False

#and运算是与运算,只有所有都为True,and运算结果才是True:
>>> True and True
True
>>> True and False
False
>>> False and False
False
>>> 5 > 3 and 3 > 1
True

#or运算是或运算,只要其中有一个为True,or运算结果就是True:
>>> True or True
True
>>> True or False
True
>>> False or False
False
>>> 5 > 3 or 1 > 3
True

#not运算是非运算,它是一个单目运算符,把True变成False,False变成True:>>> not True
False
>>> not False
True
>>> not 1 > 2
True

#条件判断中,比如:
if age >= 18:
    print('adult')
else:
    print('teenager')

 

总结

a = 1 #整数
tmp = 'T007' #字符串
alice = True #布尔

 

加(+)减(-)乘(*)除(///)模(%

#
>>>x = 10
>>>x = x + 2
x=12

#
>>>x = 10
>>>x = x - 2
x=8

#
>>>x = 10
>>>x = x* 2
x=20

#
#(/)
>>> 10 / 3
3.3333333333333335
>>> 9 / 3
3.0
#(//)
>>> 10 // 3
3    #(整数)

#
>>> 10 % 3
1    #(余数)

 

 3.字符串和编码

字符编码

用记事本编辑的时候,从文件读取的UTF-8字符被转换为Unicode字符到内存里,编辑完成后,保存的时候再把Unicode转换为UTF-8保存到文件:

rw-file-utf-8

浏览网页的时候,服务器会把动态生成的Unicode内容转换为UTF-8再传输到浏览器:

web-utf-8

所以看到很多网页的源码上会有类似<meta charset="UTF-8" />的信息,表示该网页正是用的UTF-8编码

字符串

对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符,len()函数计算str包含多少个字符:

#ord()
>>> ord('A')
65
>>> ord('')
20013
>>> chr(66)
'B'
>>> chr(25991)
''

#chr()
>>> '\u4e2d\u6587'
'中文'

#len()
>>> len('ABC')
3
>>> len('中文')
2
>>> len('中文'.encode('utf-8'))
6

格式化

在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。

>>> 'Hello, %s' % 'world'
'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
占位符替换内容
%d 整数
%f 浮点数
%s 字符串
%x 十六进制整数

 

 

 

 

如果不太确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串:

>>> 'Age: %s. Gender: %s' % (25, True)
'Age: 25. Gender: True'

有些时候,字符串里面的%是一个普通字符,这个时候就需要转义,用%%来表示一个%

>>> 'growth rate: %d %%' % 7
'growth rate: 7 %'

format()

另一种格式化字符串的方法是使用字符串的format()方法,用传入的参数依次替换字符串内的占位符{0}{1}……

>>> 'Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)
'Hello, 小明, 成绩提升了 17.1%'

 参考 https://www.liaoxuefeng.com/wiki/1177760294764384

posted @ 2020-01-19 14:57  会跳舞的猪~  阅读(191)  评论(0编辑  收藏  举报