Python自学内容总结

基础知识代码

1.字符串

'''字符串'''
print ("我叫 %s 今年 %d 岁!" % ('帅哥', 10))#字符串格式化
str1 = 'aaa'
str2 = 'sfaaasss'
'''大小写转换'''
print('第一个字母转换大写',str1.capitalize())   #字符串第一个字母转成大写
print('所有字母转换小写',str2.casefold())       #把字符串所有字符改成小写
print('大写转小写',str2.lower())                #把字符串中的大写字符变成小写
print('小写转大写',str2.upper())                #字符串中小写转成大写
'''次数查找'''

print('指定判断是否是开始的字符',str2.startswith('f',1,2))
#字符串是否是指定开头   s   从什么开始  0   到什么结束  5

print('查找出现次数',str2.count('s'))
#查找在字符串str2中 str1出现的次数
#可以在count(str1,0,10)中添加索引开始和结束

print('是否存在',str2.find('f',0,10))
#检查字符串str1是否在str2中,返回第一次出现位置,没有返回-1

print(str2.rfind(str1,0,10))#和find类似  从右往左
print('会抛出异常的find',str2.index(str1,0,20))
#和find一样,不过如果不在字符串中会抛出一个异常
print(str2.rindex(str1,0,10))#和index方法类似  从右到左


'''字符集判断和查找'''
print('类型判断,数字或者字母',str2.isalnum())
#如果字符串至少有一个字符并且所有字符都是字母或数字则
# 返 回 True,否则返回 False(相同类型)

print('所有字符都是字母',str2.isalpha())
#如果字符串至少有一个字符并且所有字符都是字母则
# 返回 True, 否则返回 False

print('只有数字','12312'.isdigit())
#如果字符串只包含数字则返回 True 否则返回 False.
print('都是小写',str2.islower())
#如果字符串中包含至少一个区分大小写的字符,
# 并且所有这些(区分大小写的)字符都是小写,

'''字符串分割填充'''
print('指定字符分割')
print(','.join(str2))
#用指定字符串分割字符串,前面的时分割符,
# 则返回 True,否则返回 False
#  后面的是被分割的字符串
print('字符串长度',len(str2))            #字符串长度
print('字符串左对齐然后填充',str2.ljust(10,'a'))
#前面是需要修改的字符串,后面是填充的东西
#使用这个方法先将字符串左对齐
#后面的(10)需要添加的字符串数量,后面的('a')是添加的字符
print('右对齐填充',str2.rjust(10,'a'))   #这个是右对其,添加10个'a'

print('截取指定字符或者空格',str.lstrip('sfaaass'))#截取字符串左边的空格或左边指定的字符
print('截取两边的字符或空格',str2.strip())
print('字符串中最大的',max(str2))            #返回字符串中最大的字符
print('字符串中最小的',min(str2 ))           #返回字符串中最小的字符

print('指定字符串内容交换',str2.replace('s','b',10))
#把字符串str2中的's',转换成'b',最多转换10次

print('指定内容作为字符串的分割符',str2.split())
#把a当成分隔符分割字符串  (一般用在字符串中有空格的时候)

元祖,List,字典

#元祖
#print('元祖开始')
tuple = ('ab',111,'bb',222,1.2)
tinytuple = (123,'aa')
print(tuple)
print(tuple[0])
print(tuple[1:3])
print(tuple[2:3])
print(tuple[2:])
print(tinytuple * 2)
print(tinytuple+tuple)
print('元祖结束')

print('set集合开始')
student = {'tom','jock','zhenni','mary','rose'}
print(student)
if 'rose' in student:
    print('rose在集合')
else:
    print('rose不再集合zhong')
a = set('ascd')
b = set('efgh')
print(a)
print(a-b)
print(a|b)
print(a^b)



dict = {}
dict['one'] = '1-可以'
dict[2] = '2-可以'
tinydict = {'name': '刘世豪' , 'id':1 , 'site' : 'www.wocao.com'}
print(dict['one'])
print(dict[2])
print(tinydict)
print(tinydict.keys())
print(tinydict.values())

#循环字符串
a = 'asdsadsa'
for i in a :
    print (end=i)

#循环列表
a =[1,2,3,4]
for i in a :
    print(i)

'''按照字符串控制循环次数----------'''
import random
a = 'asdsadsa'#字符串个数为8 循环8次  i == 5 也没用  字符串不能和数字进行比较直接忽略
for i in a:
    print(random.randint(1,10))
    if i == 5:
        break
'''使用循环测试列表------------'''
asd = ['六十','撒旦撒','撒打啥的阿斯顿是算','撒倒萨撒旦撒','撒旦撒旦撒']
for i in asd:
    print(i, len(i))#len方法输出一个列表中元素的长度
#                     #如果len方法里面是列表名  则输出列表长度

ss = 'aaa'
print('shuru')
while True:
    if ss == input():
        break
    print('输入错误')
print('成功')

for i in range(10):
    if i%2!=0:
        print(i)
        continue
    i+=2
    print(i,'aaa')
"""List方法---------------"""
list1 =[123 , 234 ]
list2 =[123, 345]
list1 *=5
print(list1 == list2)
print(dir(list))    #list里常用的方法
print(list1.count(123))     #计算元素出现次数
print(list1.index(123,4,6)) #返回索引位置  例 从4开始都6  123这个元素出现在第几个
print(list1.reverse())   #反转列表



'''list排序----------------------'''
list1 = [1 , 6 , 4 , 32 , 44 ,31 ]
for i in list1:
	print(i)
print(list1)
print(list1.sort())#列表元素从小到大排列
print(list1)
list1.sort(reverse=True)  #直接倒序排列列表
print(list1)
print(list1.reverse())#想从大到小拍需要sort排完之后在用反转方法返回
print(list1)

list2 = list1[:] #可以拷贝列表  把list1拷贝到list2


'''元组'''
temp = 1
print(temp)
print(type(temp))  #输出元素类型  这里是一个int型
temp2 =[]
print(type(temp2))  #这里是个空列表
temp3 = ()
print(type(temp3)) #这里是个空元组
temp4 = (1,)
print(temp4)
print(type(temp4))#这里是个元组
print(8*(8))     #直接做一个乘法运算   得64
print(8*(8,))    #这里定义一个元组然后元组的元素输出8次  (8,8,8,8,8,8,8)
temp5 = ('asd','dsa','ddd','rrr')
temp5 = temp5[:2] + ('hhh',) + temp5[2:]   #往元组中插入一个数据,先把元组两边拆开,然后放入元素
print(temp5)
del temp5          #删除元组  一般不用,可以自动回收

states = {
	'oregen':'OR',
	'Florida':'FL',
	'California':'CA',
	'New York':'NY',
	'Michigan':'MI'
}
#定义键值  对应的关系
cities={
	'CA':'San Francisco',
	'MI':'Detroit',
	'FL':'Jacksonville'
}

cities['NY'] = 'New YorkOne'
cities['OR'] = 'Portland'

'''字典-----------------'''
print('-1' *10)
print('NY state has :',cities['NY'])
print('OR State has :',cities['OR'])
#键是  cities['NY'] =   值是'New YorkOne'
print('-2'*10)
print("Michigan's abbreviation is : ",states['Michigan'])
print("Florida has avvreviation is :", states['Florida'])
#键是  states['Michigan'] =   值是'MI'
print('-3'*10)
print("Michign has:",cities[states['Michigan']])

print("Florida has :",cities[states['Florida']])
#键是states['Michigan'] 值是MI
# cities[MI] =   值是'Detroit'
print('-4'*10)
for state,abbrev in list(states.items()):
	print(f"{state} is abbreviatied{abbrev}")
#Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。
#把字典用for循环迭代到state,abbrev 两个变量中 ,然后输出了他们键和值 键是state  值是abbrev
print('-5'*10)
for abbrev,city in list(cities.items()):
	print(f"{abbrev} has the city{city}")
#Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。
print('-6'*10)
for state,abbrev in list(states.items()):
	print(f"{state}state is abbreviated {abbrev}")
	print(f"and has city {cities[abbrev]}")
#先取出abbrev的值  再以abbrev的值做键找到对应的值

print('-7'*10)
state = states.get('texas')
if not state:
	print('sorry , no texas.')

city = cities.get('tx','Does Not Exist')
print(f'The city for the state "tx" is "{city}')
#判断值存不存在

3.文件方法

from sys import argv

scrpit, filename = argv
# 读操作
filename="111.txt"
txt = open(filename,encoding="utf-8")

print(f'你的文件名是{filename}:')
print(txt.read())
#
print('再一次输入文件名:')
file_agin = input('>')
txt_agin = open(file_agin)
print(txt_agin.read())
from sys import argv

filename = "111.txt"
#读写操作
print(f"我们要读写的文件是{filename}")
print("你如果不想这样可以CTRL-C (^c).")
print("if you do want that , hit return(如果你想要这个 回车).")

input("?")

print("opening the file.....(打开文件)")
target = open(filename,'r+')

print("truncating thr file . goodbye(截断这个文件 再见)")
target.truncate()

print("now i'm going to ask you for three lines(现在我要问你三行)")

line1 = input("line1")
line2 = input("line2")
line3 = input("line3")

print("i'm going to write  these to the file(我去写道文件中).")
target.write(line1+'\n'+line2+'\n'+line3+'\n')

print( "and finally ,we close it(最后,我们现在把他关闭)")
str = open(filename)

target.close()

print(str.read())
from sys import argv
from os.path import exists #

from_file = "111.txt"
tofile = "222.txt"
print(f"copying from {from_file} to {tofile}")
#从 1 复制到2
#we could do these two on one line , how?
in_file = open(from_file,encoding="utf-8")
indata = in_file.read()

print(f"the input file is{len(indata)}bytes long(输入的文件时in_file文件的长度)")

print(f"daes the output file exits? {exists(tofile)}()退出了吗")
print("ready , hit return to continue , ctrl-c to abort()点击返回继续")
input()
out_file = open(tofile,'w',encoding="utf-8")
out_file.write(indata)

print("alright,all done.")

out_file.close()
in_file.close()

方法定义

from sys import argv

scricpt, input_file = argv


def print_all(f):
	print(f.read())


def rewind(f):
	f.seek(0)


def print_a_line(line_count, f):
	print(line_count, "this is ", f.readline())


current_file = open(input_file)

print("First let's rewind , kind of like a tape:倒退回去\n")
print_all(current_file)
print("now let's rewind ,kind of like a tape ")
rewind(current_file)
print("let's print three lines:")
curren_line = 1
print_a_line(curren_line, current_file)
curren_line = curren_line + 1
print_a_line(curren_line, current_file)
curren_line = curren_line + 1
print_a_line(curren_line, current_file)

def add(a,b):
	print(f"加法{a}+{b}")
	return a+b
def sub(a,b):
	print(f"减法{a}-{b}")
	return a-b
def mul(a,b):
	print(f"乘法{a}*{b}")
	return  a*b
def div(a,b):
	print(f"除法{a}/{b}")
	return a/b
print("输入数字进行计算")
aaa = add(500,400)
bbb = sub(30,20)
ccc = mul(40,60)
ddd = div(100,2)
print(f"加法:{aaa},减法:bbb:{bbb},乘法;{ccc},除法{ddd}")

print(add(aaa,sub(bbb,mul(ccc,div(ddd,2)))))
#把所有参数传一遍
#add有两个参数(第一个参数是我们第一次传入aaa计算的结果,第二个参数是第二个方法)以此类推
#分解之后大概是 add(aaa,sub(bbb,2))=add((500+400)+sub((30-20)-2))
#先运行(30-20)-2   结果8 然后是(500+400)+8
print(add(aaa,sub(bbb,2)))

def formaula(start_num):
	one = start_num *500
	two = one/1000
	three = two / 100
	return  one ,two ,three
start_num1 = 10000
first , second , third = formaula(start_num1)
print("whith a staring point of{}".format(start_num1))
print(f"we'd have {first} ,{second},{third}")

start_num1 = start_num1/10
formaula = formaula(start_num1)
print("{},{},{}".format(*formaula))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值