文章目录
字符串
字符串的创建和赋值
字符串String是由 数字, 字母, 下划线,组成的一串字符。python里面最常见的类型。可以简单的通过在引号间(单引号,双引号和三引号)包含字符串的方式创建它。
转移符号
一个反斜线加一个可以表示一个特殊字符,通常是不能打印的字符
重点演示:
字符串 的基本特征
连接操作符和重复操作符
# Pycharm常用快捷键:格式化代码符合PEP8风格(Ctrl+Alt+L)
# 1.连接操作符和重复操作符
name = 'westos'
print('hello' + name)
# print('hello' + 1 )#不同数据类型是不能相加的
print('hello' + str(1))
print("*" * 30+ '学生管理系统' + '*' * 30)
成员操作符
# 2. 成员操作符
s = 'hello westos'
print ('westos' in s) #True
print('westos' not in s) #False
print('x' in s)
#返回的是bool值
正向索引和反向索引
# 索引(s[i]) : 获取特定的偏移元素
# 索引的分类: 正向索引和反向索引
# 3.正向索引和反向索引
s = 'WESTOS'
print(s[0]) # 'W'
print(s[3]) # 'T'
print(s[-2]) # 'O'
切片
# 4.切片
"""
回顾 :
range(3):[0, 1, 2]
range(1,4):[1, 2, 3]
range(1,6,2):[1, 3, 5]
切片: 切除一部分内容
s[start:end:step]
s[:end:]
s[start:]
"""
# 总结:
# s[:n]拿出前n个元素
# s[n:]除了前n个元素,其他元素保留
# s[:] 从头开始访问一直到字符串结束的位置
# s[::-1] 倒叙输出
s = 'hello westos'
print(s[1:3]) # el
print(s[:3]) # hel
print(s[:5]) #拿出字符串的前5个字符
print(s[1:]) #ello westos
print(s[2:]) #llo westos
print(s[:]) #拷贝字符串(存在字符串的驻留机制)
print(s[::-1])
可迭代对象/for循环
# 5.for循环语句
s = 'westos'
count = 0
for item in s:
count += 1
print(f"第{count}个字符:{item}")
练习判断一个字符串是否为回文字符串
方法一:
s = input('输入字符串:')
if s == s[::-1] :
print("是回文字符串")
else:
print("不是回文字符串")
方法二:
优化方法
s = input("输入字符串:")
result = "回文字符串" if s == s[::-1] else "不是回文字符串"
print(s+result)
字符串的内建方法
字符串的判断与转化
字符串的判断
# 1.类型的判断
s = 'Hello westos'
s1 = "hellowestos"
s2 = "HAT"
print(s.isalnum())#是否为字符串或数字? false 中间存在空格
print(s.isalpha())#是否为字母? false
print(s.isdigit())#是否为数字? false
print(s1.islower())#是否为小写字母? True
print(s.isspace())# 是否为空格 false
print(s.istitle())# 是否为标题 false
print(s2.isupper())# 是否为大写字母 True
print(s.isdecimal()) # 是否为十进制字符? False
字符串的转换
# 2 .类型的转化
print ('hello'.upper()) #转换成大写字母
print ('hello WESTOS'.lower()) #转换成小写字母
print ('hello westos'.title()) #转换成标题
print ('hello westos'.capitalize()) #转换成首字母大写,其他字母小写
print ('hello wEstos'.swapcase()) #大小写反转
字符串开头和结尾的判断
# 判断startswith(开头)
url = 'http://www.baidu.com'
if url.startswith('http'):
# 具体实现爬虫,感兴趣的话可以看request模块。
print(f'{url}是一个正确的网址,可以爬取网站的代码')
# 判断endswith结尾
#常用的场景: 判断文件类型
filename = "hello.png"
if filename.endswith('.png'):
print(f'{filename}是图片文件')
elif filename.endswith('mp3'):
print(f'{filename}是音乐文件')
else :
print(f'{filename}是未知文件')
字符串的数据清洗
cmd交互式环境执行
'hello'
>>> " hello ".strip()
'hello'
>>> " hello ".lstrip()
'hello '
>>> " hello ".rstrip()
' hello'
>>> "he llo".replace(" ","")
'hello'
字符串的位置调整
"学生管理系统".center(10)
' 学生管理系统 '
"学生管理系统".center(10, "*")
'**学生管理系统**'
"学生管理系统".center(10, "-")
'--学生管理系统--'
"学生管理系统".ljust(10, "-")
'学生管理系统----'
"学生管理系统".rjust(10, "-")
'----学生管理系统'
在pycharm中需要打印输出才能有显示
print("学生管理系统".center(10))
print("学生管理系统".center(10, "*"))
字符串的搜索与统计
交互模式下执行
>>> s = "hello westos"
>>> s.find("llo")
2
>>> s.index("llo")
2
>>> s.find("xxx")
-1
>>> s.index("xxx")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.count("sss")
0
>>> s.count("ll")
1
>>> s.count("e")
2
>>>
find 如果找到子串,则返回子串开始的索引位置。否则返回-1
index如果找到子串,则返回子串开始的索引位置。否则报错(抛出异常)。
dir(s) ##查看s的方法
字符串的分割和连接
>>> ip = "172.25.254.40"
>>> item = ip.split('.')
>>> item
['172', '25', '254', '40']
>>> #拼接
>>> item
['172', '25', '254', '40']
>>> #将四个数字用-拼接起来
>>> "-".join(item)
'172-25-254-40'
练习:随机生成100个验证码:
要求:2个数字4个字母
实现流程
random.choice("0123456789")
'2'
>>> import string
>>> string.digits
'0123456789'
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> random.sample(string.ascii_letters, 4)
['Z', 'C', 'S', 'd']
>>> random.sample(string.ascii_letters, 4)
['q', 'l', 'C', 'n']
>>> "".join(random.sample(string.ascii_letters, 4))
'ENuc'
>>> random.sample(string.digits,2)"".join(random.sample(string.ascii_letters, 4))
File "<stdin>", line 1
random.sample(string.digits,2)"".join(random.sample(string.ascii_letters, 4))
^
SyntaxError: invalid syntax
>>> random.sample(string.digits,2) + "".join(random.sample(string.ascii_letters, 4))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> "".join(random.sample(string.digits,2)) + "".join(random.sample(string.ascii_letters, 4))
'82hCdU'
>>> "".join(random.sample(string.digits,2)) + "".join(random.sample(string.ascii_letters, 4))
'28VQnf'
实现代码:
import string
import random
for i in range(100):
print("".join(random.sample(string.digits,2)) + "".join(random.sample(string.ascii_letters, 4)))
快捷操作:
pip install ipython 可以对命令进行补全
设计一个题目,用来实现帮助小学生进行算术运算练习
题目要求:
“”"
设计一个题目,用来实现帮助小学生进行算术运算练习
具体功能:
提供基本算数运算(加减乘)的题目,每到题目中的操作数是随机产生的,
练习者根据显示的题目输入自己的答案,程序自动判断输入的答案是否正确
并显示相应的信息。最后显示正确率。
“”"
import random
count = int(input("请输入练习的题目数量:", ))
right_count = 0
for i in range(count ) :
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
symbol = random.choice(["+", "-", "*", "/"])
question = f"{num1} {symbol} {num2} = ?"
print(question)
i += 1
if symbol == '+':
result = num1 + num2
elif symbol == '-':
result =num1 - num2
elif symbol == '*':
result = num1 * num2
else :
result = num1 / num2
user_answer = float(input("Answer:"))
if user_answer == result:
print("Right")
right_count += 1
else:
print("Error")
print("Right percent: %.2f%%" %(right_count/count*100))
代码优化
import random
count = int(input("请输入练习的题目数量:", ))
right_count = 0
for i in range(count ) :
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
symbol = random.choice(["+", "-", "*", "/"])
question = f"{num1} {symbol} {num2} = ?"
print(question)
i += 1
result = eval(f'{num1}{symbol}{num2}')
user_answer = float(input("Answer:"))
if user_answer == result:
print("Right")
right_count += 1
else:
print("Error")
print("Right percent: %.2f%%" %(right_count/count*100))
优化方向
判断 num1 能否整除 num2
否则存在的无穷无尽的小数