本文共 6778 字,大约阅读时间需要 22 分钟。
首先列举几个这篇博客会用到的模块和函数:,,。
对于python的字符串可以参考进行学习,本篇博客将首先讲解字符串的一些相关概念和用法,之后通过几道LeetCode的题来巩固学习的知识。
字符串或串(String)是由数字、字母、下划线组成的一串字符。Python 里面最常见的类型。 可以简单地通过在引号间(单引号,双引号和三引号)包含字符的方式创建它。
字符串是不可变的,只能通过赋一个空字符串或者使用 del 语句来清空或者删除一个字符串,但是没有必要显式的删除字符串。定义这个字符串的代码结束时会自动释放这些字符串。
连接操作符: 从原有字符串获得一个新的字符串
注意:连接的也要为字符串不能是数字之类的。 重复操作符: 创建一个包含了原有字符串的多个拷贝的新串 "*“10 + “学生管理系统” + "”*10。# Pycharm常用的快捷键:# 格式化代码符合PEP8编码风格(Ctrl+Alt+L)# 1. 连接操作符和重复操作符name = 'westos'print('hello ' + name)# 1元 + 1分 = 1元 + 0.01元 = 1.01元print('hello' + str(1))print("*" * 30 + '学生管理系统' + '*' * 30)# 2. 成员操作符s = 'hello westos'print('westos' in s) # Trueprint('westos' not in s) # Falseprint('x' in s) # False# 3. 正向索引和反向索引s = 'WESTOS'print(s[0]) # 'W'print(s[3]) # 'T'print(s[-3]) # 'T'# 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])# 5. for循环访问s = 'westos'count = 0for item in s: count += 1 print(f"第{count}个字符:{item}")
# 1. 类型判断s = 'HelloWESTOS'print(s.isalnum()) # Trueprint(s.isdigit()) # Falseprint(s.isupper()) # False# 2. 类型的转换print('hello'.upper())print('HellO'.lower())print('HellO WOrld'.title())print('HellO WOrld'.capitalize())print('HellO WOrld'.swapcase())# 需求: 用户输入Y或者y都继续继续代码# yum install httpdchoice = input('是否继续安装程序(y|Y):')if choice.lower() == 'y': print("正在安装程序......")
# startswithurl = '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}是未知文件')# pycharm常用的快捷键:# 如何查看方法的源代码和解释说明: ctrl键按住,# 鼠标移动到你想要查看方法的位置,点击即可进入源码及方法说明
"""数据清洗的思路: lstrip: 删除字符串左边的空格(指广义的空格: \n, \t, ' ') rstrip: 删除字符串右边的空格(指广义的空格: \n, \t, ' ') strip: 删除字符串左边和右边的空格(指广义的空格: \n, \t, ' ') replace: 替换函数, 删除中间的空格, 将空格替换为空。replace(" ", ) >>> " hello ".strip() 'hello' >>> " hello ".lstrip() 'hello ' >>> " hello ".rstrip() ' hello' >>> " hel lo ".replace(" ", "") 'hello'"""
""">>> "学生管理系统".center(50)' 学生管理系统 '>>> "学生管理系统".center(50, "*")'**********************学生管理系统**********************'>>> "学生管理系统".center(50, "-")'----------------------学生管理系统----------------------'>>> "学生管理系统".ljust(50, "-")'学生管理系统--------------------------------------------'>>> "学生管理系统".rjust(50, "-")'--------------------------------------------学生管理系统'>>>"""
""">>> s = "hello westos">>> s.find("llo")2>>> s.index("llo")2>>> s.find("xxx")-1>>> s.index("xxx")Traceback (most recent call last): File "", line 1, in ValueError: substring not found>>> # find如果找到子串, 则返回子串开始的索引位置。 否则返回-1>>> # index如果找到子串,则返回子串开始的索引位置。否则报错(抛出异常).>>>>>> s.count("xxx")0>>> s.count("l")2>>> s.count("o")2"""
""">>> 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'>>>"""
""">>> # 需求: 生成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']>>> "".join(random.sample(string.ascii_letters, 4))'aMUF'>>> "".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4))'95sGFj'>>> for i in range(100):... print("".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4)))...53SJbP83dRcm"""
import stringidentifier = input('请输入标识符:')if len(identifier) >= 2: if identifier[0] not in string.ascii_letters + '_': print('Error:必须以字母或者下划线开始') else: for item in identifier[1:]: if item not in string.ascii_letters + string.digits + '_': print('Error:错误的标示符') break else: print('%s是正确的标示符' % (identifier))else: print('Error:错误的标示符')
验证:
简单版判断是否为回文字符串,没有加题目中的限定条件s = input('输入字符串:')result = "回文字符串" if s == s[::-1] else "不是回文字符串"print(s + "是" + result)
进阶版import stringstr = input('输入验证字符串:')if len(str) == 0: print('输出:',True)else: str = str.lower() cleanstr = '' for item in str: if item in string.ascii_letters +string.digits: cleanstr += item print('输出:', cleanstr == cleanstr[::-1])
验证:
import stringIPV4 = input('请输入IPV4:').strip()sp_IPV4 = IPV4.split('.')if len(sp_IPV4) != 4: print('Neither')else: for item in sp_IPV4: if item.startswith('0') and len(item) != 1 or not item.isdigit() or int(item) > 255: print('Neither') break else: print('IPV4')
验证:
import stringword = input('请输入单词:')if word.isupper() or word.islower() or word.istitle(): print('True')else: print('False')
验证:
record = input('出勤记录:')print(record.count('A')<=1 and record.count('LLL')<1)
验证:
move = input('请输入机器人的移动顺序:')if move.count('R') == move.count('L') and move.count('U') == move.count('D'): print('True')else: print('Flase')
验证:
import randomprint('小学生计算能力测试系统'.center(50, '*'))start = int(input("运算数的开始值:"))end = int(input("运算数的结束值:"))count = int(input("请输入测试题目数量:"))true_count = 0for item in range(count): print('第%d道:' % (item + 1), end='') num1 = random.randint(start, end) num2 = random.randint(start, end) operator = random.choice(['+', '-', '*']) print('%s %s %s = ' % (num1, operator, num2), end='') in_result = int(input()) true_result = eval('%s %s %s' % (num1, operator, num2)) if in_result == true_result: print('正确') true_count += 1 else: print('错误')print('此次测试结束,正确率: %.2f%%' % ((true_count / count) * 100))
转载地址:http://kihzi.baihongyu.com/