一、 注释

python允许在任何地方插入空字符串与注释,但不能插入到标识符和字符串中间

python注释有两种形式

  • 单行注释:以#开头的一行
  • 多行注释:被三个单引号或双引号括起来的多行
# 这是一行注释

'''
这也是一行注释
用三个单引号注释可多行内容
'''

"""
这还是一行注释
用三个双引号注释可多行内容
"""

二、 变量

1. python是弱类型语言

  • 所有变量无需声明即可使用(或者说赋值时就是声明了该变量)
  • 变量数据类型可随时改变

2. 变量赋值

  • python使用=赋值,在交互式解释器中直接输入变量名即可看到变量值
  • type()函数可以看到变量当前类型
>>> a='ffff'
>>> a
'ffff'
>>> type(a)
<class 'str'>
>>> a=2
>>> a
2
>>> type(a)
<class 'int'>

isinstance()函数可以判断变量是否为指定类型

print(isinstance(2,int))     #True
print(isinstance(2,str))     #False
print(isinstance('2',str))   #True


3. 在程序中输出变量 —— print

在python 2中print是一条输出语句,在python 3中则是一个函数

#输出单个变量
>>> a=2
>>> print(a);
2
>>> a='ffff'
>>> print(a);
ffff
#输出多个变量
>>> user_name='kkkk'
>>> user_age=8
>>> print("user_name: ",user_name,"age: ",user_age)
user_name:  kkkk age:  8

#以|分割输出
>>> print("user_name: ",user_name,"age: ",user_age,sep='|')
user_name: |kkkk|age: |8

默认情况下print输出总会换行,因为print()函数的end参数为\n,我们可以手动修改,使输出不换行

print(40,'\t',end="")
print(50,'\t',end="")
print(60,'\t',end="")
#输出 40    50    60

print默认输出到控制台,也可改变参数让print输出到文件中

f=open("test.txt","w") #文件不存在时会自动新建
print('若无闲事挂心头',file=f)
print('便是人间好时节',file=f)
f.close()

4. 变量命名规则

  • 必须以字母(英文、中文、日文等字符均可)或下划线_开头
  • 变量名可以由字母、数字、_构成,不能包含空格
  • 变量名不能为python关键字,但可以包含关键字
  • python区分大小写,aaa与AAA是不同的变量

关键字列表

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

三、 数据类型

1. 整型

python支持各种整数值,不必像其他语言区分short,int,long等,对大整数也不存在溢出问题

>>> a=56
>>> print(type(a))
<class 'int'>
>>>
>>> a=9999999999999999999999999999999999999999999999999999
>>> print(type(a))
<class 'int'>
>>> print(a)
9999999999999999999999999999999999999999999999999999

python的整型支持None值(空)

>>> a=None
>>> print(a)
None
>>> print(type(a))
<class 'NoneType'>

python整型有四种表示形式

  • 十进制:默认
  • 二进制:0b或0B开头
  • 八进制:0o或0O开头
  • 十六进制:0x或0X开头
>>> hex_val=0xAF
>>> print(type(hex_val))
<class 'int'>
>>> print(hex_val)
175
>>> bin_val=0b110
>>> print(bin_val)
6

为提高数据可读写,python支持为数值型(包括浮点数)增加下划线_作分隔符

>>> one_million=1_000_000
>>> print(one_million)
1000000
>>> price=123_456
>>> print(price)
123456

2. 浮点型

无论整型还是浮点型,python不允许除以0

两种表示形式:

  • 十进制形式:例如 5.12, 512.0, 0.512
  • 科学计数形式:例如 5.12e2(只有浮点数才允许该形式)

3. 复数

复数虚部以j或J表示

>>> ac1=3+0.2j
>>> ac2=4-0.1j
>>> print(ac1)
(3+0.2j)
>>> print(type(ac1))
<class 'complex'>
>>>
>>> print(ac1+ac2)
(7+0.1j)

4. 字符串入门

字符串与转义字符

  • 字符串可使用单引号、双引号、三个单引号、三个双引号括起来,这没有任何区别
  • 若字符串内容包含单(双)引号,则将字符串用双(单)引号括起
  • 若字符串内容单双引号都包含,可以使用\转义,或将字符串用3个引号括起
  • 若字符串内容包含\,可使用原始字符串处理(原始字符串包含的引号同样需要转义)
>>> str='"Let \'s hide in shade",says the brid'
>>> print(str)
"Let 's hide in shade",says the brid
>>> s1=r'C:\bak\test.bak'
>>> print(s1)
C:\bak\test.bak

#注意原始字符串\不能在最后,否则会将'转义掉报错
>>> s1=r'\C:\bak\test.bak\'
  File "<stdin>", line 1
    s1=r'\C:\bak\test.bak\'
                          ^
SyntaxError: EOL while scanning string literal

#正确写法应该为
>>> s1=r'\C:\bak\test.bak' '\\'
>>> print(s1)
\C:\bak\test.bak\

拼接字符串

拼接两个字符串——使用+

>>> str1="ddd"
>>> str2="kkk"
>>> print(str1+str2)
dddkkk

有种特殊写法,直接将两个字符串放在一起,python会自动拼接

>>> s1= 'aaa' 'bbb'
>>> print(s1)
aaabbb

拼接字符串与数值——必须先将数值转为字符串

       str()和repr()函数均可将数值转为字符串;str和int,float一样本身是python的内置类型;repr()是一个函数,它会以python表达式形式(将值以单引号括起)表示值。

>>> val1=34
>>> str1='fff'
>>> print(str1+val1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int

>>> print(str1+repr(val1))
fff34

>>> st='gggggg'
>>> print(repr(st))
'gggggg'
>>> print(st)
gggggg

获取用户输入

input()函数用于向用户生成一条提示,然后获取用户输入的内容,且会自动将输入内容转为字符串。python 2中提供了一个raw_input()函数,该函数就相当于python 3的input()函数。

>>> msg=input("please input a value: ")
please input a value: 6666
>>>
>>> print(msg)
6666
>>> print(type(msg))
<class 'str'>

bytes类型

python 3新增,由多个字节组成,以字节为单位进行操作(字符串则由多个字符组成,以字符为单位进行操作,其余二者基本都一样)

bytes保存的是原始的字节(二进制格式),因此bytes对象可用于在网络传递数据,也可存储各种二进制文件

将字符串转换为bytes对象有以下3种方式

  • 若字符串内容均为ASCII字符,直接在字符串前加b
  • 调用bytes()函数
  • 调用字符串本身的encode()方法
#创建一个空bytes
>>> b1 = bytes()

#创建一个空bytes
>>> b2 = b''

#创建b前缀指定hello为bytes类型值
>>> b3 = b'hello'

>>> print(b3)
b'hello'
>>> print(b3[0])
104
>>> print(b3[2:4])
b'll'

#利用bytes函数将字符串转为bytes对象
>>> b4 = bytes('我爱Python编程',encoding='utf-8')
>>> print(b4)
b'\xe6\x88\x91\xe7\x88\xb1Python\xe7\xbc\x96\xe7\xa8\x8b'

#利用字符串本身的encode()方法将字符串转为bytes对象
>>> b5 = "学习Python很有趣".encode('utf-8')
>>> print(b5)
b'\xe5\xad\xa6\xe4\xb9\xa0Python\xe5\xbe\x88\xe6\x9c\x89\xe8\xb6\xa3'

#利用bytes对象的decode()方法将其解码为字符串
>>> st = b5.decode('utf-8')
>>> print(st)
学习Python很有趣

5. 深入使用字符串

字符串格式化

python提供%对各种类型数据进行格式化输出(类似C)

>>> price=108
>>> print("the price is %s" % price)
the price is 108

上面print函数包含三部分:

  • "the price is %s" —— 格式化字符串,其中%s是一个占位符,输出结果中将会被第三部分的变量或者表达式的值代替
  • % —— 固定字符,作为分隔符
  • price —— 变量,如果前面包含多个%s,则也要对应提供多个变量并且用括号括起来。
>>> name='kkk'
>>> age=8
>>> print("the name is %s,the age is %s" % (name,age))
the name is kkk,the age is 8

python还提供了多个转换说明符

2. python 变量和简单类型_python

 

>>> num=-28
>>> print("the num is: %i" % num)
the num is: -28
>>>
>>> print("the num is: %x" % num)
the num is: -1c
>>> print("the num is: %X" % num)
the num is: -1C
>>>
>>> print("the num is: %6X" % num)
the num is:    -1C
>>> num=30
>>> print("the num is: %06d" % num)
the num is: 000030
>>> print("the num is: %+06d" % num)
the num is: +00030
>>> print("the num is: %-+06d" % num)
the num is: +30
>>>
>>> print("the num is: %-6d" % num)
the num is: 30
>>> value=3.1415926535
#最小宽度为8,小数点后留3位
>>> print("value is: %8.3f" % value)
value is:    3.142
#最小宽度为8,不足补0,小数点后留3位
>>> print("value is: %08.3f" % value)
value is: 0003.142
>>>
>>> name='asdfgh'
#最小宽度为8,保留前3个字符
>>> print("name is: %8.3s" % name)
name is:      asd
#保留前3个字符
>>> print("name is: %.3s" % name)
name is: asd

字符串序列

可以把字符串看成一个数组,通过指定下标获得对应位置字符(从0开始),另外python支持从后往前数,最后一位字符下标为-1。

>>> name='abcdefg'
>>> print(name[0])
a
>>> print(name[-1])
g

#取第4-6个字符
>>> print(name[3:5])
de

#取倒数第5-3个字符
>>> print(name[-5:-3])
cd

#取第4个及之后所有字符
>>> print(name[3:])
defg
#取前3个字符
>>> print(name[:3])
abc

#判断指定字符串是否为name子串
>>> print('abc' in name)
True
>>> print('kkk' in name)
False

#计算字符串长度
>>> print(len(name))
7

#计算字符串中最小/大值
>>> name='gfdsa'
>>> print(min(name))
a
>>> print(max(name))
s

Python帮助文档查看

dir():列出指定类或模块包含的全部内容(函数、方法、类、变量等)

help():查看某个函数、方法的帮助文档

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

>>> help(str.title)
Help on built-in function title:

title(...) method of builtins.str instance
    S.title() -> str

    Return a titlecased version of S, i.e. words start with title case
    characters, all remaining cased characters have lower case.

常用字符串方法

>>> name='aBBBBccd'
#字符串首字母大小
>>> print(name.title())
Abbbbccd
>>> print(name.lower())
abbbbccd
>>> print(name.upper())
ABBBBCCD

>>> s='  hhhdd   '
#输出时删除两边空格(不改变字符串本身)
>>> print(s.strip())
hhhdd
#输出时删除左边空格(不改变字符串本身)
>>> print(s.lstrip())
hhhdd
#输出时删除右边空格(不改变字符串本身)
>>> print(s.rstrip())
  hhhdd
>>> print(s)
  hhhdd

>>> s2='fff  gsgs'
#输出时删除两边指定字符(不改变字符串本身)
>>> print(s2.strip('s'))
fff  gsg
#可指定多个
>>> print(s2.strip('fs'))
  gsg

字符串查找替换

s='www.csdn.com'
#字符串是否以com开头
print(s.startswith('com'))       #False
#字符串是否以com结尾
print(s.endswith('com'))         #True
#csdn出现的位置
print(s.index('csdn'))           #4
#从指定位置开始找c出现的位置
print(s.find('c',6))             #9
#将所有c替换为kkk
print(s.replace('c','kkk'))      #www.kkksdn.kkkom
#将1个c替换为kkk
print(s.replace('c','kkk',1))    #www.kkksdn.com
#定义翻译映射表并进行翻译(c->α,d->β)
table={99:945,100:946}  
print(s.translate(table))        #www.αsβn.αom

字符串分割连接

s='csdn.com is aaa bbb'
#按空格分割
print(s.split())          #['csdn.com', 'is', 'aaa', 'bbb']
#按空格分割,最多只分割前2个单词
print(s.split(None,2))    #['csdn.com', 'is', 'aaa bbb']
#按.分割
print(s.split('.'))       #['csdn', 'com is aaa bbb']

mylist=s.split()
#使用/将mylist连接成字符串
print('/'.join(mylist))   #csdn.com/is/aaa/bbb

字符串重复输出

>>> s='abcd '
>>> print(s*5)
abcd abcd abcd abcd abcd

6. 比较运算符

  • ==运算符只比较两个变量的值,而is要求两个变量引用同一对象(变量内存地址相同)
  • id()函数可获取变量内存地址
>>> a=111
>>> b=111
>>> print(a==b)
True
>>> print(a is b)
True
>>> print(id(a))
1800108960
>>> print(id(b))
1800108960