python第二天--字符串

详解python中的字符串

前言

首先列举几个这篇博客会用到的模块和函数:string模块详解random模块基本用法eval函数动态计算字符串表达式

对于python的字符串可以参考python3字符串进行学习,本篇博客将首先讲解字符串的一些相关概念和用法,之后通过几道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)  # True
print('westos' not in s) # False
print('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 = 0
for item in s:
    count += 1
    print(f"第{count}个字符:{item}")

字符串内建方法

# 1. 类型判断
s = 'HelloWESTOS'
print(s.isalnum())  # True
print(s.isdigit())  # False
print(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 httpd
choice = input('是否继续安装程序(y|Y):')
if choice.lower() == 'y':
    print("正在安装程序......")

# 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}是未知文件')

# 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 "<stdin>", line 1, in <module>
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)))
...
53SJbP
83dRcm
"""

标识符(变量)合法性检查

import string

identifier = 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 string
str = 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 string

IPV4 = 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 string
word = 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 random
print('小学生计算能力测试系统'.center(50, '*'))
start = int(input("运算数的开始值:"))
end = int(input("运算数的结束值:"))
count = int(input("请输入测试题目数量:"))
true_count = 0
for 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))

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值