文章目录
pycharm中快捷键:
ctrl + alt + l 能格式化代码符合PEP8编码风格
ctrl + d能复制一行
按住ctrl键,鼠标移动到想要查看的函数上,点击就能进入该方法的源码及方法说明
dir(s)可以查看字符串变量s的可用方法。
pycharm中如何查看方法的使用帮助:
内置数据类型
- 字符串str:单引号,双引号,三引号引起来的字符信息。
- 数组array:存储同种数据类型的数据结构。[1, 2, 3], [1.1, 2.2, 3.3]
- 列表list:可以存储不同数据类型的数据结构. [1, 1.1, 2.1, ‘hello’]
- 元组tuple:和列表的唯一区别是不能增删改。
- 集合set:不重复且无序的。 (集合有交集和并集)
- 字典dict:有键值对,可以快速通过key值找到value值,{“name”:“lee”, “age”:10}
# 1. 字符串str
s1 = 'hello'
s2 = "hello"
s3 = """
*********************** 学生管理系统 ************************
"""
print(type(s1), type(s2), type(s3))
# 2. 列表List
li1 = [1, 2, 3, 4] #用中括号括起来的就是列表
print(li1, type(li1))
li2 = [1, 2.4, True, 2e+5, [1, 2, 3]]
print(li2, type(li2))
# 3. 元组tuple
# 易错点: 如果元组只有一个元素,一定要加逗号。
t1 = (1, 2.4, True, 2e+5, [1, 2, 3]) #用圆括号括起来的
print(t1, type(t1))
t2 = (1,)#元组类型
print(t2, type(t2))
t3 = (1) #int整型
print(t3, type(t3))
# 4. 集合set(无序,不重复)
set1 = {1, 2, 1, 2, 3, 1, 20}
print(set1) # 不重复{1, 2, 3,20}
set2 = {1, 2, 3}
set3 = {2, 3, 4}
print("交集:", set2 & set3) #{2,3}
print("并集:", set2 | set3) #{1,2,3,4}
# 5. 字典dict: {“name”:"westos", "age":10}
# key和value, 键值对, 通过key可以快速找到value值。
user = {"name":'westos', 'age':10}
print(user, type(user))
print(user['name'])
print(user['age'])
字符串
字符串的创建和赋值
字符串或串是由“字母、数字、下划线” 组成的一串字符。
可以通过单引号、双引号、三引号 包含字符的方式去创建
str1='we are family'
str2="we are falimy"
转义字符
\n \t 比较常用
C:\Users\wm>python
Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s="hello world"
>>> s
'hello world'
>>>
>>> s="hello\nworld"
>>> print(s)
hello
world
>>>
>>> s="hello\tworld"
>>> print(s)
hello world
>>>
字符串的基本特性
连接操作符和重复操作符
name="linux"
print("hello "+ name)
#因为1是整型,name是字符串类型,不能直接相加
#将1转换为字符串类型
print(name + str(1))
print("a"*10 + name + "b"*10)
运行结果
成员操作符
name = "hello linux"
print("linux" in name)
print("hello" not in name)
print("a" in name)
运行结果:
正向索引和反向索引
索引:获取特定偏移的元素
索引分为正向索引和反向索引。
索引在列表中有,在元组中也有
name = "hello linux"
print(name[2]) # l
print(name[5]) #空格
print(name[7]) # i
print(name[-1]) # x
print(name[-3])# n
切片
回顾:range(3) 返回的是 [0,1,2]
range(1,4) 返回的是 [1,2,3]
range(1,6,2) 返回的是 [1,3,5]
切片就是切除一部分的内容
s[start: end :step] 从start开始,以step为步长,到end-1结束
s[:end] 从头到end-1结束
s[start: ] 从start开始,到字符串完为结束
#总结
#s[:n]表示拿出前n个字符
#s[n:]表示除了前n个元素,其他元素保留
#s[:]表示从头开始访问,一直访问到字符串结束为止,遍历字符串
#s[::-1]表示倒叙输出
name = "hello linux"
print(name[1:4])#ell
print(name[:3])#hel
print(name[:5])#拿出字符串的前5个字符,hello
#总结
#s[:n]表示拿出前n个字符
#s[n:]表示除了前n个元素,其他元素保留
#s[:]表示从头开始访问,一直访问到字符串结束为止
#s[::-1]表示倒叙输出
print(name[1:]) #ello linux
print(name[:2]) #he
print(name[:]) #hello linux ,拷贝字符串
print(name[::-1]) #倒序输出
运行结果:
可迭代对象/for循环
name = "hello"
count=0
for item in name:
count+=1
print(f"第{count}个字符为{item}")
小练习:判断字符串是否为回文字符串
str=input("请输入一个字符串:")
#str2=str[:] #字符串的正序输出
str1=str[::-1] #字符串的倒序输出
if str == str1:
print(f"字符串{str}是回文字符串")
else:
print(f"字符串{str}不是回文字符串")
运行结果:
考虑使用三元运算符
str=input("请输入一个字符串:")
#str1=str[:] #字符串的正序输出
result="是回文字符串"if str == str[::-1] else "不是回文字符串"
print(str+"是"+result)
运行结果相同
练习-输入正整数,判断对应的二进制是否为回文,使用算法思想实现
num=int(input("请输入一个数:"))
bin_num=bin(num)[2:] #将该整数转换为二进制,由于二进制存储为0b开头,因此从第二位开始取
#print(bin_num)
#print(bin_num[2])#bin_num的第三位
#print(bin_num[-1])#bin_num的倒数第一位
for item in range(len(bin_num)):
if (bin_num[item] != bin_num[-1-item]):#bin_num[item]正序遍历,bin_num[-1-item]倒序遍历
print(f"{num}的二进制为{bin_num},不是回文字符串")
exit()
print(f"{num}的二进制为{bin_num},是回文字符串")
运行结果:
字符串的内置方法
字符串的判断与转换
判断字符类型
- isalnum:是否为数字或字母
- isalpha:是否为字母
- isdigit:是否数字
- islower:是否小写字母
- isspace:是否空格
- istitle:是否标题,标题:若干个单词组成,每个单词首字母大写。比如:Hello World
- isupper:是否大写字母
- isdecimal:是否是十进制字符
str1="helloLINUX"
str2="hello LINUX"
print(str1.isalnum()) #true
print(str2.isalnum()) #false,因为有空格
print(str1.isalpha()) #true
print(str1.isupper()) #false
运行截图:
形式转换
- lower:转换成小写字母
- upper:转换成大写字母
- title:转换成标题
- swapcase:大小写反转
- capitalize:只有首字母大写,其余字母均小写
print("HEllo".upper()) #HELLO
print("HELLO".lower()) #hello
print("hello linux".title()) #Hello Linux
print("hello linux".capitalize()) #Hello linux
print("HEllo LINux".swapcase()) #heLLO linUX
#使用场景:比如用户安装httpd,yum install httpd
choice=input("是否继续安装程序(y|Y|N|n):")
if choice.lower()=="y":
print("正在安装程序")
else:
print("终止安装程序")
运行截图:
字符串的开头和结尾匹配
- startswith:是否以指定字符串开头
- endswith:是否以指定字符串结尾
url="http://www.baidu.com"
if url.startswith("http"):
#爬虫需要用到request模块
print(f"{url}是一个正确的网址,可以爬取网站的代码")
else:
print(f"{url}网址错误")
filename="hello.txt"
if filename.endswith("txt"):
print(f"{filename}是一个文本文件")
elif filename.endswith("jpg"):
print(f"{filename}是一个图片")
elif filename.endswith("mp4"):
print(f"{filename}是一个音频文件")
else:
print(f"{filename}文件类型未知")
字符串的数据清洗
下述的空格是指广义上的空格,比如 \n换行 和\t制表符 以及空格本身
- strip:删除字符串开头和末尾的空格(\n、\t 、’ ')
- lstrip:删除字符串开头的空格(\n、\t 、’ ')
- rstrip:删除字符串末尾的空格(\n、\t 、’ ')
- replace:字符串替换。如果要删除中间的空格,可以将空格替换为空
print(" hello ".strip()) #清空字符串左边和右边的空格
print(" hello".lstrip()) #清空字符串左边的空格
print(" hello ".rstrip()) #清空字符串右边的空格
print("hel lo".replace(" ","")) #将字符串中间的空格替换为空
字符串的位置调整
- center(width):字符串居中且长度为指定宽度
- ljust(width):字符串左对齐,且长度为指定宽度
- rjust(width):字符串右对齐,且长度为指定宽度
print("欢迎登录".center(50)) #总长度为50,字符串居中,其余位置使用空格补齐
print("欢迎登录".center(50,"*")) #总长度为50,字符串居中,其余位置使用*补齐
print("欢迎登录".ljust(50,"-")) #总长度为50,字符串左对齐,其余位置使用-补齐
print("欢迎登录".rjust(50,"*")) #总长度为50,字符串右对齐,其余位置使用*补齐
字符串的搜索与统计
- find(str, beg, end): 在字符串中查找子串,返回位置
- index(str, beg, end) :找不到子串就会返回错误,有异常
- count(str, start, end)
s = "this is a string"
print(s.find("is")) #返回子串的首个位置
print(s.index("is")) #返回子串的首个位置
print(s.find("aaa")) #find找不到子串,会返回-1
print(s.index("aaa")) #index找不到子串,就会报错
s = "this is a string"
print(s.count("is")) #返回子串的出现次数
print(s.count("oo")) #返回子串的出现次数
字符串的分离和拼接
- split(str=" "):使用str为分隔符,对字符串切片
- splitines() : 对字符串切片
- join() :使用连接符将多个字符串连接在一起
#需求:对IP地址的合法性检查
#将IP的每一位数字拿出,判断每个数字是否在0-255之间
ip = "192.168.1.100"
items=ip.split(".") #分离
print(items) #['192', '168', '1', '100']
print("-".join(items)) #用-将items拼接
拓展:string模块(生成随机验证码)
string.digits 返回数字
string.ascii_letters 返回所有字母
string.ascii_uppercase 返回所有大写字母
string.ascii_lowercase 返回所有小写字母
random.sample 从一个序列中返回几个随机值
random.choice 从一个序列中返回一个随机值
random.randint(1,10) 从区间1到10之间,返回一个随机整数
生成100个验证码:每个验证码由6个字符组成,包括2个数字+4个字母
#方法一:使用random.choice以及for循环也能实现,但是比较麻烦
import random
print(random.choice("0123456789")) #random.choice选出一个随机值
print(random.choice("0123456789")+random.choice("0123456789"))
print(random.choice("0123456789")+random.choice("0123456789")+random.choice("abcdefgh"))
#方法二:string模块
import random
import string
print(string.digits) #生成所有数字
print(string.ascii_letters) #生成所有字母
#random.sample(list,4)表示从列表list中随机选取4个元素
print(random.sample(string.ascii_letters,4))
for i in range(100):
print("".join(random.sample(string.ascii_letters, 4)) + "".join(random.sample(string.digits, 2)))
运行截图:
练习-小学生算数运算练习系统
"""
设计一个程序,用来实现帮助小学生进行算术运算练习,它具有以下功能:
提供基本算术运算(加减乘)的题目,每道题中的操作数是随机产生的,练习者根据显示的题目输入自己的答案,
程序自动判断输入的答案是否正确并显示出相应的信息。最后显示正确率。
"""
import random
count = 10
right_count = 0
for i in range(count):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
operator = random.choice(["+", "-", "*"])
print(f"{num1}{operator}{num2} = ?")
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
answer = int(input("请输入你的解答:"))
if answer == result:
print("正确")
right_count += 1
else:
print("错误")
print("正确率为:%.2f %%"%(right_count/count*100))
可以使用eval算法做运算,更简单:
result=eval(f"{num1}{operator}{num2}")
练习-ipv4地址合法性检测
"""
编写一个函数来验证输入的字符串是否是有效的 IPv4 ?
1). IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(".")分割。
比如,172.16.253.1;
2). IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。
"""
ip = input("请输入字符串:")
num="".join(ip.strip().split(".")) #num type:string
while num.isdigit():
list = ip.strip().split(".") #list类型
for item in list:
if int(item) <= 0 or int(item) >= 255:
print("IP地址不合格,数字范围为0-255")
exit()
elif item.startswith("0"):
print("IP地址不合格,不能以0开头")
exit()
print("IP地址合格")
exit()
else:
print("输入错误,IP应为数字")
exit()
运行截图:
练习-检测是否为回文字符串,只考虑字母和数字,忽略字母大小写
"""
给定一个字符串,验证它是否是回文字符串,只考虑字母和数字,忽略字母大小写
本题中,将空字符串定义为有效的回文字符串
"""
test_str = input("请输入一个字符串:")
tem_str = test_str.strip().replace(" ", "") # 清除字符串开头、末尾的空格,使用空代替字符串中间的空格
item = tem_str.lower() # 将字符中的所有字母都转换为小写字母
new_item = filter(str.isalnum, item) #过滤出字符串中的字母和数字
new_str="".join(list(new_item))
#print(new_str)
if new_str == new_str[::-1]:
print("该字符串为回文字符串")
else:
print("该字符串不是回文字符串")
运行截图: