文章目录
- 前言
- 1、字符串的基本特性
- 1.1 连接操作符和重复操作符
- 1.2 成员操作符
- 1.3 正向索引和反向索引
- 1.4 切片
- 1.5 for循环访问
- 1.6 小习题
- 2、字符串的判断和转换
- 2.1 类型判断
- 2.2 类型的转换
- 2.3 小练习
- 3、字符串开头和结尾的判断
- 4、字符串的数据清洗
- 5、 字符串的位置调整
- 6、字符串的搜索和统计
- 7、 字符串的分离和拼接
- 8、随机生成验证码
- 9、课后练习题
- 9.1 小学生计算能力测试系统
- 9.2 IPV4合法性判断
- 9.3 机器人能否返回原点
前言
Pycharm常用的快捷键:
- 格式化代码符合PEP8编码风格(Ctrl+Alt+L)
- 如何查看方法的源代码和解释说明:
ctrl键按住,鼠标移动到你想要查看方法的位置,点击即可进入源码及方法说明
1、字符串的基本特性
1.1 连接操作符和重复操作符
name = 'westos'
print('hello ' + name)
# 1元 + 1分 = 1元 + 0.01元 = 1.01元
print('hello' + str(1))
print("*" * 30 + '学生管理系统' + '*' * 30)
运行效果:
1.2 成员操作符
判断成员是否属于检测目标,以bool形式输出
s = 'hello westos'
print('westos' in s) # True
print('westos' not in s) # False
print('x' in s) # False
运行效果:
1.3 正向索引和反向索引
不指定默认0 1 2 3 这样从0 开始索引
加“-”号代表倒着数,这时候倒数第一个就是第一个
s = 'WESTOS'
print(s[0]) # 'W'
print(s[3]) # 'T'
print(s[-3]) # 'T'
print(s[-1]) # 'S'
运行效果:
1.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[:-n] 除了后n个元素, 其他元素保留
s[:] 从头开始访问一直到字符串结束的位置
s[::-1] 倒序输出
"""
s = 'hello westos'
print(s[1:3]) # 'el'
print(s[:5]) # 拿出字符串的前5个字符
print(s[1:]) # 'ello westos'
print(s[:-1]) # ‘hello westo’
print(s[2:]) # 'llo westos'
print(s[:]) # 拷贝字符串
print(s[::-1]) # 倒着打印
运行效果:
1.5 for循环访问
s = 'westos'
count = 0
for item in s:
count += 1
print(f"第{count}个字符:{item}")
运行效果:
1.6 小习题
判断回文字符串
s = input('输入字符串:')
result = "回文字符串" if s == s[::-1] else "不是回文字符串"
print(s + "是" + result)
运行测试(利用三元运算符优化代码):
while True:
s = input('输入字符串:')
print("是回文字符串" if s==s[::-1] else "不是回文字符串")
2、字符串的判断和转换
2.1 类型判断
可以自动补齐,不用强记,巧记:s是字母/数字/大写字母/…吗?
输出为bool型
s = 'HelloWESTOS'
print(s.isalnum()) # True
print(s.isdigit()) # Flase
print(s.isupper()) # False
运行效果:
2.2 类型的转换
转换格式,一般大小写转换居多
print('hello'.upper())
print('HellO'.lower())
print('HellO WOrld'.title())
print('HellO WOrld'.capitalize())
print('HellO WOrld'.swapcase())
测试效果:
s = 'hello wEStos'
print(s.upper())
print(s.lower())
print(s.title())
print(s.capitalize())
测试效果:
2.3 小练习
# 需求: 用户输入Y或者y都继续继续代码
# yum install httpd
choice = input('是否继续安装程序(y|Y):')
if choice.lower() == 'y':
print("正在安装程序......")
修改为测试语句(方便测试):
while True:
choice = input('是否继续安装程序(y|Y):')
if choice.lower() == 'y':
print("正在安装程序......")
3、字符串开头和结尾的判断
# 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}是未知文件')
运行效果:
4、字符串的数据清洗
"""
数据清洗的思路:
lstrip: 删除字符串左边的空格(指广义的空格: \n, \t, ' ')
rstrip: 删除字符串右边的空格(指广义的空格: \n, \t, ' ')
strip: 删除字符串左边和右边的空格(指广义的空格: \n, \t, ' ')
replace: 替换函数, 删除中间的空格, 将空格替换为空。replace(" ", )
>>> " hello ".strip()
'hello'
>>> " hello ".lstrip()
'hello '
>>> " hello ".rstrip()
' hello'
>>> " hel lo ".replace(" ", "")
'hello'
"""
测试语句:
s=' hello linux '
print(s.lstrip())
print(s.rstrip())
print(s.strip())
print(s.replace(" ",""))
运行效果:
5、 字符串的位置调整
"""
>>> "学生管理系统".center(50)
' 学生管理系统 '
>>> "学生管理系统".center(50, "*")
'**********************学生管理系统**********************'
>>> "学生管理系统".center(50, "-")
'----------------------学生管理系统----------------------'
>>> "学生管理系统".ljust(50, "-")
'学生管理系统--------------------------------------------'
>>> "学生管理系统".rjust(50, "-")
'--------------------------------------------学生管理系统'
>>>
"""
改成测试语句:
print("学生管理系统".center(50))
print("学生管理系统".center(50, "*"))
print("学生管理系统".center(50, "-"))
print("学生管理系统".ljust(50, "-"))
print("学生管理系统".rjust(50, "-"))
运行结果:
6、字符串的搜索和统计
"""
#搜索
>>> 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
>>> # find如果找到子串, 则返回子串开始的索引位置。 否则返回-1
>>> # index如果找到子串,则返回子串开始的索引位置。否则报错(抛出异常).
#统计
>>> s.count("xxx")
0
>>> s.count("l")
2
>>> s.count("o")
2
"""
测试:
s = 'hello westos'
print(s.find('llo'))
print(s.find('xxx'))
print(s.index('llo'))
print(s.index('xxx'))
运行效果:
7、 字符串的分离和拼接
"""
>>> ip = "172.25.254.100"
>>> # 需求:IP地址的合法性-将ip的每一位数字拿出, 判断每位数字是否在0-255之间。
>>> ip.split('.')
['172', '25', '254', '100']
>>> items = ip.split('.')
>>> items
['172', '25', '254', '100']
>>> # 拼接
>>> items
['172', '25', '254', '100']
>>> # 需求: 将四个数字用'-'拼接起来
>>> "-".join(items)
'172-25-254-100'
>>>
"""
改个测试语句:
while True:
ip = input('please input IP:')
ip1 = ip
items = ip1.split('.')
for i in range(len(items)):
if 0 < int(items[i]) < 255:
continue
else:
i += 1
break
print("此IP合法" if i == 3 else "该IP不合法")
运行效果:
8、随机生成验证码
"""
>>> # 需求: 生成100个验证码, 每个验证码由2个数字和2个字母组成。
>>>
>>>
>>>
>>> import random
>>> random.choice("0123456789")
'6'
>>> random.choice("0123456789") + random.choice('0123456789')
'84'
>>> random.choice("0123456789") + random.choice('0123456789') + random.choice('abcdef')
'16b'
>>> import string
>>> string.digits
'0123456789'
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> random.sample(string.ascii_letters, 4)
['z', 'N', 'u', 't']
>>> random.sample(string.ascii_letters, 4)
['c', 'q', 'X', 'f']
>>> random.sample(string.ascii_letters, 4)
['D', 'b', 'e', 'A']
>>> "".join(random.sample(string.ascii_letters, 4))
'aMUF'
>>> "".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4))
'95sGFj'
>>> "".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4))
'17TlIb'
>>> "".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4))
'50uvqM'
>>> "".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4))
'09MCDW'
>>> "".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4))
'83Wntf'
>>> for i in range(100):
... print("".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4)))
...
53SJbP
83dRcm
"""
9、课后练习题
9.1 小学生计算能力测试系统
设计一个程序,用来实现帮助小学生进行算术运算练习,
它具有以下功能:
提供基本算术运算(加减乘)的题目,每道题中的操作数是随机产生的,
练习者根据显示的题目输入自己的答案,程序自动判断输入的答案是否正确
并显示出相应的信息。最后显示正确率。
1+2=?
3*6=?
初版:
import random
count = 10
right_count = 0
for i in range(count):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
symbol = random.choice(["+", "-", "*"])
if symbol == "+":
result = num1 + num2
elif symbol == "-":
result = num1 - num2
elif symbol == "*":
result = num1 * num2
question = f"{num1} {symbol} {num2} = ?"
print(question)
user_answer = int(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 = 10
right_count = 0
for i in range(count):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
symbol = random.choice(["+", "-", "*"])
result = eval(f"{num1}{symbol}{num2}")
question = f"{num1} {symbol} {num2} = ?"
print(question)
user_answer = int(input("Answer:"))
if user_answer == result:
print("Right")
right_count += 1
else:
print("Error")
print("Right percent: %.2f%%" %(right_count/count*100))
9.2 IPV4合法性判断
编写一个函数来验证输入的字符串是否是有效IPv4?
- IPv4地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为0-255,用“.”分割
比如, 172.254.25.168; - IPv4地址内的数不会以0开头。比如,地址172.16.254.01是不合法的。
原题链接
ip = input('please input IP:')
# ip = '192.168.1.2'
items = ip.split('.')
for i in range(len(items)):
if int(items[i]) > 254 or items[i].startswith('0'):
print("该IP不合法")
exit()
else:
continue
print("此IP合法")
9.3 机器人能否返回原点
a=input("输入动作[R]右 [L]左 [D]下 [U]上:")
r=l=d=u=0
for i in a:
if i=="R":
r+=1
elif i=="L":
l+=1
elif i=="D":
d+=1
elif i=="U":
u+=1
else:
print("请输入正确的字符!")
exit()
print(" true " if r==l and u==d else "false")