Python 官方文档:入门教程 => 点击学习
练习题:1. 26个字母大小写成对打印,例如:Aa,Bb.... for i in range(65,91): print(chr(i)+chr(i+32)+",",end="") 2、一个list包含10个数字,然后生成新的lis
练习题:
1. 26个字母大小写成对打印,例如:Aa,Bb....
for i in range(65,91):
print(chr(i)+chr(i+32)+",",end="")
2、一个list包含10个数字,然后生成新的list,要求,新的list里面的数都比之前的数多1
list_1 = list(range(10))
result = []
for num in list_1:
result.append(num + 1)
print(result)
print([num + 1 for num in list_1])
3、倒序取出每个单词的第一个字母。
s = "I am a Good boy "
s_list = s.split()
for i in range(len(s_list)-1,-1,-1):
print(s_list[i][0])
s = "I am a boy!"
s=s.split()
s.reverse()
result = []
for i in s:
result.append(i[0])
print(result)
4、找出s=”aabbccddxxxxffff”中,出现次数最多的字母
#coding=utf-8
s="aabbccddxxxxffff"
letter_numbers = {}
for c in s:
letter_numbers[c] = s.count(c)
max_times = max(letter_numbers.values())
for k,v in letter_numbers.items():
if v == max_times:
print(k)
5、自定义count函数
只统计单个字符出现次数情况
#coding=utf-8
a = “a1111bceDDD”
def count_letters(s,letter):
times = 0
if not isinstance(s,str) or not isinstance(letter,str):
return 0
else:
for v in s:
if v == letter:
times += 1
return times
print(count_letters(a,1))
兼容统计多个字符出现次数的情况
算法:
1、首先求出需要查找字符串的长度
2、遍历源字符串,如果当前索引加上子串长度对应的字符串等于要查找字符串的话次数加1
#encoding=utf-8
def count_letters(s,letter):
times = 0
letter_length = len(letter)
if not isinstance(s,str) or not isinstance(letter,str):
return 0
if letter not in s:
return 0
else:
for i in range(len(s)):
if s[i:i+letter_length] == letter:
#判断当前索引+字符串长度是否等于要查找的字符串
times += 1
return times
s = "abcabdab1"
print(count_letters(s,"ab"))
数学运算符:
math.ceil()向上取整
math.ceil(5//2)
2
math.ceil(5/2)
3
math.floor()向下取整
import math
math.floor(1.9/2)
0math.ceil(1.9/2)
1
math.round(0.5)round(5.1112,2)
5.11
divmod()同时求商和余数
divmod(5,2)
(2, 1)
练习题:
自定义divmod
#coding=utf-8
def divmod_2(a,b):
c = a//b
d = a%b
return c,d
print(divmod_2(5,2))
幂
2**3
8
a.zfill(length)
a 的长度如果小于length,左边补0,总长度是length
bin(5)[2:]
'101'
bin(5)[2:].zfill(8)
'00000101'
int()函数携带base参数
int(bin(3),base=2)#把二进制转换成10进制
3int("10",base=16)#把16进制转成10进制
16
int("10",16)
16int("10",8)
8
int("10",base=8)
8
False取值
0 "" [] () {} None False
--结束END--
本文标题: python3学习(3)
本文链接: https://lsjlt.com/news/192959.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0