单行注释 #
# 开始学习python啦,第一行代码是学会打印hello world,print('hello world!')
print('hello world!')
'''
今天是周二
开始学习python啦
坚持就是胜利
'''
# 或者
"""
这是多行注释
编程机器不会运行的模块
但是程序员可以通过这来了解我们为什么这样写代码
"""
print('好好学习,天天向上')
print('good good study,day day up!')
print('''This is a really really
really really long line of
code.''')
print\
("""his is a really really
really really long line of
code.""")
total = item_one + \
item_two + \
item_three
for i in range(10):
print('我要学习python')
if 1>2:
print('true')
else:
print('false')
也许这里会更好理解,print(‘true’)与print(‘false’)这两行有相同的缩进,缩进了4个空格,代表的是同一个代码块。缩进的空格数可以变,但是同一个代码块缩进数应该一样,否则代码无法正常运行,会提示异常。
for i in range(10):
print('hello world!')
import keyword
tmp = keyword.kwlist
print(tmp)
其中
type(2)
type(2.1)
type(None)
type('hello world')
-共同点:两者都可以判断对象类型
-不同点:type()不会认为子类是一种父类类型,isinstance()会认为子类是一种父类类型。
Python 有两种错误:语法错误和异常。
在编写 python 程序时如果不注意语法的正确使用,在程序运行时就会出现错误,这种错误属于语法错误。
如上,字符串的右侧少了个引号,程序便无法执行了,并给出相关的错误信息:语法错误。
错误信息会告诉你错误位于哪个文件,出现在哪一行,以及属于什么类型。
针对这种语法错误,我们可以找到出错的地方,相应地去修改,就可以正常运行了
而 python 中不属于语法错误的错误,就是异常(exception)。
出现异常时,Python 程序会说“Python(或程序)报了一个异常”
比如不小心把0用作分母,就会出现“ZeroDivisionError”异常
比如代码缩进不正确,程序会报“IdentationError”
操作符 | 含义 | 示例 | 结果 |
---|---|---|---|
** | 指数运算 | 2**3 | 8 |
% | 取模运算,即取余数 | 14%4 | 2 |
// | 整除运算,即取整数 | 14//4 | 3 |
/ | 除法运算,返回浮点数 | 13/8 | 1.625 |
* | 乘法运算 | 8*2 | 16 |
- | 减法运算 | 7-1 | 6 |
+ | 加法运算 | 2+3 | 5 |
操作符 | 含义 | 示例 | 结果 |
---|---|---|---|
> | 大于 | 100>10 | True |
< | 小于 | 100<10 | False |
>= | 大于等于 | 2>=2 | True |
<= | 小于等于 | 1<=4 | True |
== | 等于 | 6==9 | False |
!= | 不等于 | 3!=2 | True |
操作符 | 含义 | 示例 | 结果 |
---|---|---|---|
and | 与(都真才真) | True and True | True |
or | 或(一真则真) | True or False | True |
not | 非 | not True | False |
操作符 | 说明 | 示例 | 结果 |
---|---|---|---|
= | 简单的赋值操作符 | a=3 | 把3赋值给a |
+= | 加法赋值操作符 | a+=3 | 把a+3的值赋给a,即a=a+3 |
-= | 减法赋值操作符 | a-=1 | 把a-1的值赋给a,即 a=a-1 |
*= | 乘法赋值操作符 | a*=2 | 把a2的值赋给a,即 a=a2 |
/= | 除法赋值操作符 | a/=2 | 把a/2的值赋给a,即a=a/2 |
%= | 取模赋值操作符 | a%=2 | 把a%2的值赋给a,即 a=a%2 |
//= | 取商赋值操作符 | a//2 | 把a//2的值赋给a,即 a=a//2 |
**= | 幂赋值操作符 | a**=2 | 把a**2的值赋给a,即 a=a%2 |
:= | 海象运算符 | 可在表达式内部为变量赋值。` |
if bool(conj):
do something
以上伪代码(伪代码是用于解释说明示例代码的标记方法)中 bool(conj) 是一个判断条件,结果是 True 或者 False ,如果是 True ,就会执行 do something 这条语句,否则不返回任何值。
值得注意的是,if 语句之后的冒号 :必须要有,执行语句(do something 那行)前面需要缩进4个空格,一个Tab键,很多编译器会自动缩进,没有的话需要自己特别注意,否则会提示缩进错误
if 1>2 :
print('True')
else:
print('False')
if 条件1:
语块1
elif 条件2:
语块2
elif 条件3:
语块3
...
else:
语块4
number=input('please enter a number:')
# input函数用于用户输入内容
number=int(number)
# input返回的结果都是字符串,需要用int函数把用户输入的内容转为数字类型
if number == 10 :
print('this number is {}'.format(number))
elif number > 50 :
print('this number is {}'.format(number))
print('this number is more than 50')
elif number > 10 :
print('this number is {}'.format(number))
print('this number is more than 10')
else:
print('this number is {}'.format(number))
print('this number is less than 50')
A=Y if X else Z
x=2
y=4
a='python' if x>y else 'hello'
print(a)
b='python' if x<y else 'hello'
print(b)
# 第一题
print('hello world')
print('good good study')
print('day day up')
# 第二题
num_1=int(input('please enter a number'))
if num_1 < 10 :
print('您输入的数字是{},小于10'.format(num_1))
else:
print('您输入的数字是{},大于等于10'.format(num_1))
# 第三题
num_1=int(input('please enter a number'))
if num_1 <= 10 :
print('您输入的数字是{},小于等于10'.format(num_1))
elif num_1 <=25 :
print('您输入的数字是{},小于等于25'.format(num_1))
else:
print('您输入的数字是{},大于25'.format(num_1))
# 第四题,第五题
num_1=20
num_2=7
num_3=num_1%num_2
print(num_3)
num_4=num_1//num_2
print(num_4)
age=int(input("请输入你的年龄:"))
if age<=0:
print("请输入正确的年龄:")
elif age<=18:
print("你的年龄是{},未成年".format(age))
elif age<=40:
print("你的年龄是{},还年轻,继续拼搏".format(age))
elif age<=60:
print("你的年龄是{},注意养生了吗".format(age))
else:
print("你的年龄是{},祝您身体健康哦".format(age))
num_1=2
num_1=2.1
整型(Int)
a=input('请输入一个数字:')
a=int(a)
b=float(a)
函数 | 返回值 |
---|---|
abs(x) | 返回数字的绝对值,如abs(-10) 返回 10 |
ceil(x) | 返回数字的上入整数,如math.ceil(4.1) 返回 5 |
floor(x) | 返回数字的下舍整数,如math.floor(4.9)返回 4 |
exp(x) | 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045 |
fabs(x) | 返回数字的绝对值,如math.fabs(-10) 返回10.0 |
log(x) | 如math.log(math.e)返回1.0,math.log(100,10)返回2.0 |
log10(x) | 返回以10为基数的x的对数,如math.log10(100)返回 2.0 |
max(x1, x2,…) | 返回给定参数的最大值,参数可以为序列。 |
min(x1, x2,…) | 返回给定参数的最小值,参数可以为序列。 |
pow(x, y) | x**y 运算后的值。 |
round(x [,n]) | 返回浮点数 x 的四舍五入值,如给出 n 值,则代表舍入到小数 |
sqrt(x) | 返回数字x的平方根。 |
函数 | 说明 |
---|---|
choice(seq) | 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。 |
randrange ([start,] stop [,step]) | 从指定范围内,按指定基数递增的集合中获取一个随机数,基数默认值为 1 |
random() | 随机生成下一个实数,它在[0,1)范围内。 |
seed([x]) | 改变随机数生成器的种子seed。如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed。 |
shuffle(lst) | 将序列的所有元素随机排序 |
uniform(x, y) | 随机生成下一个实数,它在[x,y]范围内。 |
函数 | 说明 |
---|---|
acos(x) | 返回x的反余弦弧度值。 |
asin(x) | 返回x的反正弦弧度值。 |
atan(x) | 返回x的反正切弧度值。 |
atan2(y, x) | 返回给定的 X 及 Y 坐标值的反正切值。 |
cos(x) | 返回x的弧度的余弦值。 |
hypot(x, y) | 返回欧几里德范数 sqrt(xx + yy)。 |
sin(x) | 返回的x弧度的正弦值。 |
tan(x) | 返回x弧度的正切值。 |
degrees(x) | 将弧度转换为角度,如degrees(math.pi/2) , 返回90.0 |
radians(x) | 将角度转换为弧度 |
常量 | 说明 |
---|---|
pi | 数学常量 pi(圆周率,一般以π来表示) |
e | 数学常量 e,e即自然常数(自然常数)。 |
# 以求圆周率为例子
import math
math.pi
dir(math)
help(math.exp)
string_1='I love python'
string_2="我爱学习"
len(string_1)
len(string_2)
type(string_1)
print('what's your name?')
果然呀!出现了语法错误,SyntaxError: invalid syntax
编写这段程序时,我们涉及三个单引号(一对半),python解析器是看不懂的,它会以为前面两个单引号才是一对,而后面单个单引号则会让python解析器的迷惑,因为语法上是不能出现单个引号的,于是python解析器报了个语法错误。
那么我们应该怎么解决这个问题呢?方法有二
方法一:双引号包裹单引号
print("what's your name?")
print("what\'s your name?")
以下介绍比较常用的转义类型
转义字符 | 说明 |
---|---|
\(在行尾时) | 续行符 |
\\ | 转义反斜杠符号 |
\’ | 转义单引号 |
\" | 转义双引号 |
\a | 响铃,执行后电脑会有提示音 |
\b | 退格(Backspace) |
\000 | 空 |
\n | 换行 |
\v | 纵向制表符 |
\t | 横向制表符 |
\r | 回车,将 \r 后面的内容移到字符串开头,并逐一替换开头部分的字符,直至将 \r 后面的内容完全替换完成。 |
\f | 换页 |
\oyy | 八进制数,y 代表 0~7 的字符,例如:\012 代表换行。 |
\xyy | 十六进制数,以 \x 开头,y 代表的字符,例如:\x0a 代表换行 |
\other | 其它的字符以普通格式输出 |
例子
# 续行,第1章所提到的实现多行语句
print("line1 \
line2 \
line3")
line1 line2 line3
# 反斜杠
print("\\")
# 单引号
print('\'')
# 双引号
print("\"")
# 铃声,执行后电脑有响声。
print("\a")
# 退格
print("Hello \b World!")
#结果:Hello World!
# 空,输出结果什么也没有
print("\000")
# 换行
print("\n")
# 纵向制表符
print("Hello \v World!")
# 横向制表符
print("Hello \t World!")
# 回车
print("Hello\rWorld!")
print("Hello who are you\rWorld!")
# 换页
print("Hello \f World!")
操作符 | 说明 |
---|---|
+ | 字符串连接 |
* | 重复输出字符串 |
[] | 通过索引获取字符串中的字符 |
[:] | 截取字符串中的一部分,遵循左闭右开原则,str[0:2] 是不包含第 3 个字符的。 |
in | 成员运算符 - 如果字符串中包含给定的字符返回 True |
not in | 成员运算符 - 如果字符串中不包含给定的字符返回 True |
r/R | 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母 r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。 |
a = "Hello"
b = "Python"
print("a + b 输出结果:", a + b)
print("a * 2 输出结果:", a * 2)
string_1='today is a nice day!'
string_2='Let\'s study'
print(string_1+string_2)
print(string_2*10)
print('*'*1000)
dos="c:\new\study\python"
string = 'python'
做例子string='study python'
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
---|---|---|---|---|---|---|---|---|---|---|---|
s | t | u | d | y | p | y | t | h | o | n | |
-12 | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
正索引: 从第1个字符开始到最后一个字符结束(从左到右编号),编号从0开始,以此类推,如上字符串“s”编号0,"t"编号1,……
负索引: 从倒数第一个字符开始到第一个字符结束(从右到左编号),编号从-1开始,以此类推,如上字符串“n“编号为-1,”o“编号为-2,……
值得注意的是: 空格也属于一个字符
那么索引有什么用呢?
通过索引我们可以找到该索引所对应的字符
string='study python'
string[1]
string[-6]
# 上面介绍过,我们可以利用符号 [] 通过索引获取字符串中的字符
string.index('t')
示例中有两个“t”,但结果只返回了正索引的第一个,找到就结束了程序。
了解了索引,是时候了解切片了
所谓切片是指通过索引对字符串进行全部或部分的截取,得到新的字符串,但不改变原来的字符串,这就是字符串切片。
string='study python'
#输出字符串
print(string)
#输出第一个到倒数第二个的所有字符
print(string[0:-1])
#输出字符串第一个字符(左边开始数)
print(string[0])
#输出从第一个开始后的所有字符
print(string[0:])
#输出从第三个开始后的所有字符
print(string[2:])
#输出从第四个开始到第七个的字符,步长为1
print(string[3:7:1])
#输出从第四个开始到第七个的字符,步长为2
print(string[3:7:2])
#输出从第四个开始到倒数第一个的字符,默认步长为1
print(string[3:-1])
#输出从第四个开始到第七个的字符
print(string[3:7])
#截取字符串的全部范围
print(string[::])
#截取字符串的范围,步长为1
print(string[::1])
#截取字符串的范围,步长为2
print(string[::2])
#字符串翻转,步长为1
print(string[::-1])
#字符串翻转,步长为2
print(string[::-2])
#输出字符串两次
print(string*2)
#连接字符串
print(string+'你')
print('---')
print('---'*20)
string='study python'
'p' in string
'study' in string
' ' in string
'u' not in string
# 单个字符比较
"a">"b"
"a"<"b"
"a"=="b"
# 字符串比较
"abc">"aaa"
"abc">"zc"
使用占位符 %
string1="love"
print("%s"%string1)
print("%8s"%string1)
print("%-8s"%string1)
英文不好还可以找翻译
S.format(*args, **kwargs) 括号里是方法的参数,参数的形式有 *args 和 **kwargs 两种
*args 表示传入的参数形如(“python”,“Java”),这个很好理解,就是传入两个普通的对象——字符串,当然也可以是数字类型等,后面再讲。
**kwargs 表示出入的参数形如 (hot=“python”,normal=“java”),这个对我们小白来说可能有点难理解,都不知道是什么来的,其实这是一种“字典“类型的格式化输出,先把它记住,后面学习字典再来
下面进入示例
"I'am a {0} and I like {1}".format("green hand","python")
"I'am a {1} and I like {0}".format("python","green hand")
"I'am a {0:15} and I like {1:>15}".format("green hand","python")
"I'am a {0:.2} and I like {1:^10.4}".format("green hand","python")
这里又多了点东西——小圆点(.)
{0:.2} 中冒号与小圆点之间没有数字,即没有字符的长度要求;{1:^10.4} 中冒号与小圆点之间有(^10),意思是字符串长度为10,对应的参数输出应该是居中对齐,查看结果确实是居中
好,那么小圆点是啥意思呢?
对字符串的格式化输出来说,小圆点表示字符串的截取,小圆点后面的数字表示字符串截取的长度。
(.2)是指对字符串进行2个字符的截取,所以格式化输出的结果是(gr)
(.4)是对字符串截取4个字符,所以输出内容是(pyth),居中对齐
它们都是从第一个字符进行截取的。
format 方法不仅可以传入字符串,也可以传入数字(包括整型和浮点型),而且都可以有一定的格式花样。请看例子!
"She is {0:4d} years old and she is {1:f}m tall".format(14,1.632415)
"She is {0:4d} years old and she is {1:6.2f}m tall".format(14,1.632415)
"She is {0:04d} years old and she is {1:06.2f}m tall".format(14,1.632415)
设置长度要求前多了个0,意思是在数字前面,如果位数不够,用0填充。
讲了这么多,还是有点疲惫呀!总结一下format这一块,参数的形式 args 和 **kwargs 只是了解了args部分,还有 **kwargs 部分没了解,未来有期!
help(str.capitalize)
方法 | 用途 |
---|---|
str.upper | 将字符串的字母全转成大写 |
str.lower | 将字符串的字母全转成小写 |
str.capitalize | 将首字母转换为大写 |
str.title | 将字符串中所有单词的首字母大写,而其他字母小写 |
str.isupper | 判断字符串的字母是否全部是大写 |
str.islower | 判断字符串字母是否全部都是小写 |
str.istitle | 判断字符串是否标题模式,即字符串中所有单词的首字母是大写,而其他字母是小写 |
string0=string.upper()
string="study python"
string="stuDy Python"
string0=string.upper()
string1=string.lower()
string2=string.capitalize()
string3=string.title()
print(string,\n,string0,\n,string1,\n,string2,\n,string3)
a=string.isupper()
b=string0.islower()
c=string2.istitle()
print(a,b,c)
判断方法 | 用途 |
---|---|
str.isalnum | 判断字符串是否全部由字母和数字组成 |
str.isalpha | 判断字符串是否全部由字母组成 |
str.isdigit | 判断字符串是否全部由数字组成 |
user_input=input("请输入信息:")
if user_input.isalpha():
print("您的输入全是字母")
elif user_input.isdigit():
print("您的输入全是数字")
elif user_input.isalnum():
print("您的输入包括字母和数字")
else:
print("您的输入不是由字母和数字组成")
string="I love python and I will study python with my heart."
a=str.split(string)
string="I love python and I will study python with my heart."
a=string.split()
string="I love python and I will study python with my heart."
a=string.split()
b=string.split(" ") # 直接设置空格为分隔符,默认分割到最后
c=string.split("and") # 以 and 进行分割字符串,默认分割到最后
d=string.split(" ",4) # 以空格分割字符串,分割4次,得到5个元素
去除空格方法 | 用途 |
---|---|
str.strip() | 去除字符串左右两边空格 |
str.lstrip() | 去除字符串左边空格 |
str.rstrip() | 去除字符串右边空格 |
string=" He is a stupid boy "
string_0=string.strip()
string_1=string.lstrip()
string_2=string.rstrip()
print(string)
print(string_0)
print(string_1)
print(string_2)
拼接字符串
string="I love python"
"".join(string) # 不设置分隔符,默认不用分割,直接拼接各个元素并输出
" ".join(string) # 设置分隔符为一个空格,可迭代对象的每个元素会以空格连接起来组成一个新的字符串输出
".".join(string) # 设置分隔符为一个小圆点 . ,可迭代对象的每个元素会以小圆点 . 连接起来组成一个新的字符串输出
"!".join(string) # 设置分隔符为 !
tu=(1,2,3,4,"haha","la",9)
;如果元祖只有一个元素,后面也要跟个逗号:tu_1=("haha",)
.tu_0=("hello","python") # 创建元祖
string=" ".join(tu_0) # 以空格将元祖的元素拼接起来组成一个新的字符串,并赋给变量 string
string=",I love ".join(tu_0) # 把分隔符设置成一个字符串(其实分隔符本身就是字符串)将元祖的元素拼接输出
string=":".join(tu_0) # 分隔符为 :
a=" 您好 "
a.join(tu_0)
string="I love python and I will study python with my heart." # 创建字符串
list_0=string.split() # 分割字符串
print(list_0)
string_1=" ".join(list_0) # 拼接字符串
print(string_1)
a=string==string_1 # 判断原字符串与新建的字符串是否一样
# 按照语法 str.replace(self, old, new, count=-1, /)
string="I love python and I will study python with my heart."
new_string=str.replace(string,"I","小七黛")
new_string_1=str.replace(string,"I","小七黛",1)#替换1次
string="I love python and I will study python with my heart."
new_string=string.replace("I","小七黛")
new_string_1=string.replace("I","小七黛",2)
new_string=string.replace("my"," ")
new_string=string.replace(" "," ")
# 第一题
string_1="Camus"
string_2=" ".join(string_1) #添加分隔符
list_1=string_2.split() # 进行分割字符串
print(list_1) # 得到的列表就是字符串的所有字母
# 如果想把字符串的字符一个一个的打印,可使用遍历
for i in string_1:
print(i)
# 第二题
user_enter_1=input("Please enter what you wrote yesterday:")
user_enter_2=input("Please enter the person you contated yesterday:")
print("Yesterday I wrote a {0}. I sent it to {1}"\
.format(user_enter_1,user_enter_2))
# 第三题
string_3="aldous Huxley was born in 1894."
string_3=string_3.capitalize()
print(string_3)
# 第四题
string_4="Where now? Who now? When now?"
string_4=string_4.replace("?","??",2)
string_4=string_4.split("? ")
print(string_4)
# 第五题
list_5=["The", "fox", "jumped", "over", "the", "fence", "."]
string_5=" ".join(list_5)
string_5=string_5.replace(" .",".")
print(string_5)
# 第六题
string_6="A screaming comes across the sky."
string_6=string_6.replace("s","$")
print(string_6)
'''
第七题
找到字符串"Hemingway"中字符"m"所在的第一个索引。
以上的字符串方法中,我并没有提过寻找索引的方法,
但既然题目都说了这是字符串的方法,那可以先调用字符串的库查看一下有关索引的方法
然后根据内置函数 help() 查看用途用法
'''
索引 | 说明 |
---|---|
S.index(sub[, start[, end]]) -> | 查找的是最低的那个索引 |
S.rindex(sub[, start[, end]]) -> int | 查找的是最高的那个索引 |
# 第七题
"Hemingway".index("m")
# 第八题
print\
('''
a说:“如果你不违背我,你要什么我就能给你什么,你要什么都可以,
把你的心给我吧”
b说:“我甚至连他的一张照片都没有,他只活在我的记忆里”
经典:一个人一生可以爱上很多人,等你获得真正属于你的幸福以后,
你就会明白以前的伤痛其实是一种财富,它让你更好的把握和珍惜你爱的人
''')
# 第八题
string_8="three"
string_8=(string_8+" ")*2+string_8
print(string_8)
# 第九题
string_9="It was bright cold day in April, \
and the clocks were striking thirteen."
a=string_9.index(",")
string_9=string_9[:a]
print(string_9)
lst_1=list()
lst_2=[]
lst_3=[2021,"小七黛","女","Amethyst bead",[1,2,3,4],True,False,60] #列表存放了数字、字符串、布尔型、列表
type(lst_1)
type(lst_2)
type(lst_3)
# 使用type() 查看对象类型
bool(lst_1)
bool(lst_2)
bool(lst_3)
string_0="python" # 创建字符串
lst_0=["python",20,"study",9.9] # 创建列表
string_0[0] # 取字符串索引为0的元素
lst_0[0] # 取列表索引为0的元素
string_0="python" # 创建字符串
lst_0=["python",20,"study",9.9] # 创建列表
string_1=string_0[:]
lst_1=lst_0[2:4]
lst_2=lst_0[2:3]
lst_3=lst_0[::2]
lst_4=lst_0[::]
string_0="python" # 创建字符串
lst_0=["python",20,"study",9.9] # 创建列表
string_1=string_0[::-1]
lst_1=lst_0[::-1]
补充:reversed() 反转函数
string_0="python" # 创建字符串
lst_0=["python",20,"study",9.9] # 创建列表
lst_1=list(reversed(string_0)) # 反转字符串,并把逐个元素存放在lst_1列表中
lst_2=list(reversed(lst_0)) # 反转列表
lst_1=[1,3,5,7,9]
print(lst_1)
a=lst_1.reverse()
print(a)
print(lst_1)
lst_1=[1,3,5,7,9]
b=reversed(lst_1)
print(lst_1)
print(b)
print(list(b))
函数 | 共同点 | 区别 |
---|---|---|
reversed() | 反序 | 内置函数,返回迭代器类型的对象,需要使用list()函数转换输出,不改变原列表 |
list.reverse() | 反序 | 列表的一个方法,返回值为None,改变原列表 |
方法 | 说明 |
---|---|
L.append() | 在列表最后追加一个元素,每次一个!改变原列表 |
L.extend() | 在列表的最后扩容,extend传入可迭代对象,并把可迭代对象的元素逐个追加到列表中,改变原列表,不改变传入对象 |
lst_1=[1,2,3,4,5,6]
lst_2=["study","python","mysql"]
string_1="xiaoqidai"
string_2="135"
int_1=23
float_1=9.99
# 使用 append
lst_1.append(lst_2) # 把对象 lst_2 追加到列表 lst_1 中
print(lst_1)
lst_1.append(string_1) # 把对象 string_1 追加到列表 lst_1 中
print(lst_1)
lst_1.append(int_1) # 把对象 int_1 追加到列表 lst_1 中
print(lst_1)
lst_1.append(float_1) # 把对象 float_1 追加到列表 lst_1 中
print(lst_1)
print("*"*100)
# 使用 extend
lst_1.extend(lst_2) # 把列表 lst_2 中的元素全都添加到列表 lst_1 中
print(lst_1)
lst_1.extend(string_1) # 把列表 string_1 中的元素全都添加到列表 lst_1 中
print(lst_1)
lst_1.extend(string_2) # 把列表 string_2 中的元素全都添加到列表 lst_1
print(lst_1)
lst_1.extend(int_1) # int_1 不是可迭代对象,此处会报错,同样的float_1也不是可迭代对象,不能通过 extend 方法添加到列表中
print(lst_1)
字符串方法 count
help(str.count)
string_1="python python python"
len(string_1) # 计算字符串的字符长度,以估算截取片段的位置
t=string_1.count("p",0,10) #从字符串的索引为0的位置开始,到索引为10的位置结束,统计p 出现的次数
string_1[10] # 查看 索引为10的位置是哪个字符,大概就知道索引为10是中间python的那个 t 了
t=string_1.count("t",0,10) #从字符串的索引为0的位置开始,到索引为10的位置结束,统计 t 出现的次数,如果是1次,那就是左开右闭原则,即,截取的片段开始位置包括 0 ,结束位置不包括10
t=string_1.count("t",10) # 当后面只给出一个参数的时候,默认为这是截取字符串开始的位置,一直到最后才结束
t=string_1.count("p",10)
t=string_1.count("n",10)
列表方法 count
lst_1=string_1.split() # 利用字符串的分割函数,创建一个列表
print(lst_1)
lst_1.extend(["study",1,3,5,"hard"]) # 给列表再添点数据
lst_1.append("study") # 再追加一个
print(lst_1)
lst_1.count("python") # 统计列表中的元素 python 出现了几次
lst_1.count("study") # 统计列表中的元素 study 出现了几次
lst_1.count("1") #这里统计的是字符串 “1“ 出现的次数,并不是数字1,而列表中没有出现字符串”1”,所以这里结果是0
lst_1.count(1) #统计整型 1 在列表中出现的次数
lst_1.count("python",1) # 检验一下,是否可以截取片段,结果报错,列表的count函数只能接受一个参数
lst_1=['python', 'python', 'python', 'study', 1, 3, 5, 'hard', 'study']
lst_1.index("python")
lst_1.index("1")
lst_1.index(1)
help(list.insert)
lst_1=['python', 'python', 'python', 'study', 1, 3, 5, 'hard', 'study']
list.insert(lst_1,len(lst_1)-1,"done") # 在列表的最后一个元素前插入对象“done“
# 以上写法 insert传入了3个参数,第一个是操作的列表,第二个是索引,第三个是插入对象。
#另一种写法
lst_1.insert(len(lst_1),"done") # 这种情况只能传入两个参数,一个索引,一个插入对象。
help(list.remove)
help(list.pop)
lst_1=["python","mysql","python","java","xiaoqidai","python"]
lst_2=["python","mysql","python","java","xiaoqidai","python"]
lst_1.remove("python")
lst_1.remove("java")
lst_1.remove("java")
lst_2.pop(2)
lst_2.pop()
lst_2.pop(0)
lst_2.pop(1)
lst_2.pop(len(lst_2)+1)
lst_1=[1,6,7,4,5,6,2,9]
lst_2=["python","java","C+","mysql"]
lst_3=["python","java","C+","mysql",80,85,90,100,96]
lst_1.sort()
lst_2.sort()
lst_3.sort()
lst_2=["python","java","C+","mysql","p","pp","pz"]
lst_2.sort()
设置条件排序
lst_2=["python","java","C+","mysql","p","pp","pz"]
lst_2.sort(key=len)
lst_2=["python","java","C+","mysql","p","pp","pz"]
lst_2.sort(key=len,reverse=True)
lst_1.sort(key=len,reverse=True)
lst_2=['python', 'mysql', 'java', 'C+', 'pp', 'pz', 'p']
lst_2[0]="change"
duowei_1=[[1,2,3],[3,5,9],[0,6,4]]
duowei_1[1][0]
列表与字符串的转换
str.split()
"[sep]".join(list)
t=12,'hello',9.9,True,[1,3,"python"]
print(t)
type(t)
tuple_1=tuple()
tuple_2=()
tuple_3=(2,)
tuple_4=(2)
type(tuple_3)
type(tuple_4)
tuple_1=(1,3,'python','hello')
tuple_1=list(tuple_1)
tuple_1=[1, 3, 'python', 'hello']
tuple_1=tuple(tuple_1)
name=([1,"python"],[2,"java"])
course=dict(name) # 使用函数 dict() 强制把元祖转换为字典,需注意元祖的结构
dt=dict(name="John",age=23) # 使用函数 dict() 创建非空字典
person={"name":"Mike","age":18,"phone":"123-999"}
person["name"]
操作 | 说明 |
---|---|
len(d) | 返回字典(d)中的键值对的数量 |
d[key] | 返回字典(d)中的键(key)所对应的值(value) |
d[key]=value | 将值(value)赋给字典中的键(key),创建或修改的键值对 |
del d[key] | 删除字典(d)的键(key)所对应的键值对 |
key in d | 检查字典是否含有键为key的项 |
person={"name":"Mike","age":18,"phone":"123-999"}
len(person)
person['age']
person["study"]="python"
del person['phone']
"name" in person
"phone" in person
person['age']=20
my_information={'name':'Mery','time':'moroning','age':'19','phone':'222-888-999','country':'China','sex':'girl'}
introduce='''
Good {time},everybody!
My name is {name}.I'am {age} years old,a sunshine {sex},come from {country}.
That's all,thank you!
'''
print(introduce.format(**my_information))
a={1:'string',2:'list',3:'tuple'}
print(a)
a.clear()
print(a)
del a
print(a)
a={1:'string',2:'list',3:'tuple'}
print(a)
print(id(a))
b=a.copy()
print(b)
print(id(b))
b['title']='python'
print(b)
print(a)
get
a={1:'string',2:'list',3:'tuple','total':['python','mysql']}
print(a.get('total'))
print(a.get('python'))
print(a.get(3,'无'))
print(a.get(4,'无'))
print(a['total'])
print(a['python'])
setdefault
a={1:'string',2:'list',3:'tuple','total':['python','mysql']}
print(a)
print(a.setdefault(2))
print(a)
print(a.setdefault(4))
print(a)
print(a.setdefault('title','python'))
print(a)
dd={'major':'python','web':'www.runoob.com','name':'xiaoqi'}
dd_items=dd.items()
dd_values=dd.values()
dd_keys=dd.keys()
print(dd_items)
print(dd_values)
print(dd_keys)
dd={'major':'python','web':'www.runoob.com','name':'xiaoqi'}
print(dd)
a=dd.pop('name')
print(dd)
print(a)
b=dd.pop('age','none')
print(dd)
print(b)
dd={'major':'python','web':'www.runoob.com','name':'xiaoqi'}
print(dd)
dd_delete=dd.popitem()
print(dd)
print(dd_delete)
dd={'major':'python','web':'www.runoob.com','name':'xiaoqi'}
print(dd)
dd_update=dd.update([('age','12')])
print(dd)
dd_update=dd.update({1:'nihao',2:'hello'})
print(dd)
s1=set()
s2=set('hello')
s3=set((1,2,3,4))
s4=set(["ab","hello"])
s5={}
s6={1,"hello",("word",)}
s7={["lazy"],1,"hello",("word",)}
f_set=frozenset('hello')
a_set=set('hello')
"h" in a_set
"H" in a_set
"H" not in a_set
(1)等于:A是否等于B
a_set=set('hello')
b_set=set('ohel')
a_set == b_set
a_set != b_set
a_set=set('hello')
b_set=set('hol')
b_set < a_set
a_set < b_set
b_set.issubset(a_set)
c_set=set("hole")
a_set<c_set
a_set=set('hello')
b_set=set('python')
new_set=a_set|b_set
new_set_2=a_set.union(b_set)
a_set=set('hello')
b_set=set('python')
c=a_set & b_set
d=a_set.intersection(b_set)
a_set=set('hello')
b_set=set('python')
c=a_set - b_set
c=b_set - a_set
c=a_set.difference(b_set)
(5) A 、 B 的对称差集,即 A 有的 B 没有与 B 有的 A 没有的并集
a_set=set('hello')
b_set=set('python')
c=a_set - b_set
d=b_set - a_set
all_set=c|d
a=[1,2,3]
hasattr(a,'__iter__')
import collections
isinstance('hello',collections.Iterable)
# python3.8 以上版本可使用如下表达,因为以上表达即将被停用。
isinstance('hello',collections.abc.Iterable)
string_1='zhutou'
for i in string_1:
print(i)
lst_1=['he','is','a','nice','boy']
for i in lst_1:
print(i)
tup_1=(10,15,12,9)
for i in tup_1:
print(i)
# 返回键一
dic_1={'who':'zhutou','what':'love','how':'well'}
for i in dic_1:
print(i)
# 返回键二
for i in dic_1.keys():
print(i)
# 返回值一
for i in dic_1:
print(dic_1[i])
# 返回值二
for i in dic_1.values():
print(i)
# 返回键与值
for k,v in dic_1.items():
print(k,v)
a=range(10)
lst_1=list(a)
lst_2=list(range(0,10,2))
range(1,10,3)
# 方法一
lst=[]
for i in range(100):
if i % 2 == 0:
lst.append(i)
print(lst)
# 方法二
lst_2=list(range(0,100,2))
print('lst_2=',lst_2)
a=['age','name','job']
b=['18','Mary','student']
t=zip(a,b)
print(t,'/n',type(t))
a=['age','name','job']
b=['18','Mary','student']
# 把a,b成组以列表形式显示
lst=list(zip(a,b))
# 把a,b以字典的键值对形式显示
d=dict(zip(a,b))
print(lst)
print(d)
a=[1,3,5,7,9]
b=[2,4,6,8,10]
# 方法1
lst=[]
for i in range(len(a)):
lst.append(a[i]+b[i])
print(lst)
# 方法2
lst=[]
for x,y in zip(a,b):
lst.append(x+y)
print(lst)
a=[('age', '18'), ('name', 'Mary'), ('job', 'student')]
for i,s in enumerate(a):# i 对应可迭代对象的索引,s 对应可迭代对象的元素
print(i,s)
[i for i in range(100) if i % 2 ==0]
data={"id":1,"f_name":"Jonathan","m_name":None,"l_name":"Hsu"}
data_1={k:v for k,v in data.items() if v != None }
print(data_1)
dd={'python':89,'java':58,'physics':65,'math':49,'chinese':78}
scores=dd.values() # 获取所有值
mean=sum(scores)/len(scores) # 计算平均分
print(mean)
dd_mean={k:v for k,v in dd.items() if v>mean} # 字典解析
print(dd_mean)