博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python第二天--字符串
阅读量:3961 次
发布时间:2019-05-24

本文共 6778 字,大约阅读时间需要 22 分钟。

python第二天--字符串

详解python中的字符串

前言

首先列举几个这篇博客会用到的模块和函数:,,。

对于python的字符串可以参考进行学习,本篇博客将首先讲解字符串的一些相关概念和用法,之后通过几道LeetCode的题来巩固学习的知识。

字符串的创建和赋值

字符串或串(String)是由数字、字母、下划线组成的一串字符。Python 里面最常见的类型。 可以简单地通过在引号间(单引号,双引号和三引号)包含字符的方式创建它。

  • 转义符号
    一个反斜线加一个单一字符可以表示一个特殊字符,通常是不可打印的字符

字符串是不可变的,只能通过赋一个空字符串或者使用 del 语句来清空或者删除一个字符串,但是没有必要显式的删除字符串。定义这个字符串的代码结束时会自动释放这些字符串。

字符串的基本特性

连接操作符: 从原有字符串获得一个新的字符串

注意:连接的也要为字符串不能是数字之类的。
重复操作符: 创建一个包含了原有字符串的多个拷贝的新串
"*“10 + “学生管理系统” + "”*10。

  • 索引
  1. 索引(s[i] ): 获取特定偏移的元素,默认初始位置为0。
  2. 索引的分类: 正向索引, 反向索引,对于反向索引,最后一位为-1。
  • 切片
  1. 切片S[i:j]提取对应的部分作为一个序列:
  2. 如果没有给出切片的边界,切片的下边界默认为0,上边界为字符串的长度;扩展的切片S[i:j:k],其中i,j含义同上,k为递增步长;
  3. s[:]获取从偏移量为0到末尾之间的元素,是实现有效拷贝的一种方法;
  4. s[::-1]是实现字符串反转的一种方法;
# 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个验证码

""">>> # 需求: 生成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])

验证:

IPV4合法性判断

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')

验证:

检测大写字母 detect-capital

import stringword = input('请输入单词:')if word.isupper() or word.islower() or word.istitle():    print('True')else:    print('False')

验证:

学生出勤记录 student-attendance-record

record = input('出勤记录:')print(record.count('A')<=1 and record.count('LLL')<1)

验证:

机器人能否返回原点 robot-return-to-origin

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/

你可能感兴趣的文章
[闲话] 在西方的程序员眼里,东方的程序员是什么样的
查看>>
[管理] 成功之路的探寻 —— “三力” 理论
查看>>
[连载] Socket 深度探索 4 PHP (一)
查看>>
[无线] Android 系统开发学习杂记
查看>>
[无线] 浅析当代 LBS 技术
查看>>
[杂感] 缅怀乔布斯
查看>>
[无线] 让Android支持cmwap上网
查看>>
[无线] AndroidManifest.xml配置文件详解
查看>>
[移动] Mosquitto简要教程(安装/使用/测试)
查看>>
[HTML5] 关于HTML5(WebGL)的那点事
查看>>
自我反思
查看>>
初识网络编程
查看>>
东北赛选拔教训
查看>>
hash
查看>>
涨姿势了:求两个分子的最大公倍数
查看>>
快速幂
查看>>
vector.reserve and resize &&vector与map结合
查看>>
最长公共子序列
查看>>
计算几何
查看>>
求解方程
查看>>