python合集(3)-------字符串

1.字符串的创建和赋值

字符串或串(String)是由数字、字母、下划线组成的一串字符。Python 里面最常见的类型。 可以简单地通过在引号间(单引号,双引号和三引号)包含字符的方式创建它
第一种方式:
str1 = ‘our company is westos’
第二种方式:
str2 = “our company is westos”
第三种方式:
在这里插入图片描述

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

在这里插入图片描述

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

2.字符串的基本特性

连接操作符:
从原有字符串获得一个新的字符串,连接符 :(+),且连接类型要相同
重复操作符:
创建一个包含了原有字符串的多个拷贝的新串,重复操作符:(*)

索引:
索引(s[i] ): 获取特定偏移的元素,默认初始位置为0。 索引 包括: 正向索引, 反向索引,对于反向索引,最后一位为-1。

切片:

  1. 切片S[i:j]提取对应的部分作为一个序列:

  2. 如果没有给出切片的边界,切片的下边界默认为0,上边界为字符串的长度;扩展的切片S[i:j:k],其中i,j含义同上,k为递增步长;

  3. s[:]获取从偏移量为0到末尾之间的元素,是十分有效拷贝的一种方法; s[::-1]是实现字符串反转的一种方法

成员操作符:
判断一个字符或一个子串(中的字符)是否出现在另一个字符中,出现返回Ture,反之为False

# 1. 连接操作符和重复操作符
name = 'zl'
print('haha ' + name)
print("*" * 30 + '学生管理系统' + '*' * 30) :用乘号形式让其重复出现

# 2. 成员操作符
yum = 'zl haha'
print('haha' in yum)  # True
print('haha' not in yum) # False
print('x' in yum) # False

# 3. 正向索引和反向索引
s = 'WESTOS'
print(s[0])  # 'W' #:0号索引对应的字符是
print(s[3]) # 'T' # :3号索引对应的字符是
print(s[-3]) # 'T' # :倒数第三个字符是

# 4. 切片
"""
回顾: 
    range(3):[0, 1, 2]
    range(1, 4): [1, 2, 3]
    range(1, 8, 2): [1, 3, 5,7]
切片: 切除一部分的内容
    s[start:end:step]
    s[:end]:
    s[start:]:
总结: 
    s[:n]: 拿出前n个元素
    s[n:]: 除了前n个元素, 其他元素保留
    s[:]:从头开始访问一直到字符串结束的位置
    s[::-1]: 倒序输出
"""
s = 'haha zl'
print(s[1:3]) # 'aha'
print(s[:3]) # 'haha'
print(s[:4])  # 拿出字符串的前4个字符
print(s[1:])  # 'aha zl'
print(s[:])   # 拷贝字符串
print(s[::-1]) #倒序输出字符串
# 5. for循环访问
s = 'westos'
count = 0
for item in s:
    count += 1
    print(f"第{count}个字符:{item}")

3.字符串的内建方法

3.1.字符串的判断与转换

在这里插入图片描述

1.判断
s = 'hahaWESTOS'
print(s.isalnum())  # True
print(s.isalpha())  # True
print(s.isdigit())  # Flase
print(s.isupper())  # False
print(s.islower())  # False
print(s.isspace())  # False
2.转换
print('westos'.upper()) :转换为大写字母
print('LINUX'.lower())  :转换为小写
print('westos linux'.title())  :转换为标题WESTOS LINUX
print('HellO WOrld'.capitalize()) :首字母为大写,其余为小写Hello world
print('HellO WOrld'.swapcase()) :大写转换为小写,小写转换为大写hELLo woRLD

3.2 字符串的开头与结尾匹配

在这里插入图片描述
startswith
一些网址的开头是http,用来判断网址的正确性

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

3.3 字符串的位置调整

在这里插入图片描述

center(width)	:字符串居中且长度为指定宽度
ljust(width)	:字符串左对齐且长度为指定宽度
rjust(width)	:字符串右对齐且长度为指定宽度
print("westoslinux".center(20))
print("westoslinux".center(20,"#"))
print("westoslinux".ljust(20,"#"))
print("westoslinux".rjust(20,"#"))
结果:
D:\python\python.exe C:/Users/萧然之雪/PycharmProjects/pythonProject/6-21/数据清洗.py
    westoslinux     
####westoslinux#####
westoslinux#########
#########westoslinux

3.4字符串的数据清洗

在这里插入图片描述

数据清洗的思路 :
lstrip: 删除字符串左边的空格(指广义的空格: \n, \t, ’ ')
rstrip: 删除字符串右边的空格(指广义的空格: \n, \t, ’ ')
strip: 删除字符串左边和右边的空格(指广义的空格: \n, \t, ’ ')
replace: 替换函数, 删除中间的空格, 将空格替换为空。replace(" ", )

print(" westos ".strip())
print(" westos ".lstrip())
print(" westos".rstrip())
print(" wes  tos ".replace(" ", ""))
结果:
D:\python\python.exe C:/Users/萧然之雪/PycharmProjects/pythonProject/6-21/数据清洗.py
westos
westos 
 westos
westos

3.5 字符串的搜索与统计

在这里插入图片描述

s = "linux westos"
print(s.find("linux"))#Linux字符是从第0个索引开始
#print(s.find("hello")):find查找的结果不存在,返回-1
print(s.index("linux"))#Linux字符是从第0个索引开始
#print(s.index("hello")) :index查找的结果不存在,报错
print(s.count("linux")):linux字符出现1#print(s.count("hello"))
结果:
D:\python\python.exe C:/Users/萧然之雪/PycharmProjects/pythonProject/6-21/数据清洗.py
0  
0
1

3.6字符串的分离与拼接

在这里插入图片描述

ip = "172.25.6.1" 
print(ip.split('.')) #以'.'为分隔符切片
item = ip.split('.')
print(f'{item}')
print("-".join(item)) #以'-'连接
结果:
D:\python\python.exe C:/Users/萧然之雪/PycharmProjects/pythonProject/6-21/数据清洗.py
['172', '25', '6', '1']
['172', '25', '6', '1']
172-25-6-1

4.string模块

需求: 生成验证码,验证码由3个数字和3个字母组成
import random #random模块可以随机生成数字,但较为繁琐
print(random.choice("0123456789") + random.choice('0123456789') + random.choice('abcdef'))
结果:
D:\python\python.exe C:/Users/萧然之雪/PycharmProjects/pythonProject/6-21/数据清洗.py
68a
import random
import string #string 模块中有随机生成数字string.digits和字母的模块string.ascii_letters:
print("".join(random.sample(string.digits, 3)) + "".join(random.sample(string.ascii_letters, 3)))
结果:
D:\python\python.exe C:/Users/萧然之雪/PycharmProjects/pythonProject/6-21/数据清洗.py
438Civ

测试

测试1

设计一个程序,用来实现帮助小学生进行算术运算练习
它具有以下功能:
提供基本算术运算(加减乘)的题目,每道题中的操作数是随机产生的,
练习者根据显示的题目输入自己的答案,程序自动判断输入的答案是否正确
并显示出相应的信息。最后显示正确率。

import  random

count = 10
right_count = 0
for item in range(count):
    num1 = random.randint(1,10)
    num2 = random.randint(1,10)
    symbol = random.choice(["-","*","+"])
    right_answer = eval(f"{num1}{symbol}{num2}")
    question = f"{num1} {symbol} {num2} = ?"
    print(question)
    user_answer = int(input("answer:"))
    if user_answer == right_answer:
        print("user_answer is right")
        right_count +=1
    else:
        print("user_answer is error")
print(f"right percent:%0.1f%%" % (right_count/count*100))

测试2

判断ip合法性:
ip = “172.25.6.1”
需求:IP地址的合法性-将ip的每一位数字拿出, 判断每位数字是否在0-255之间。

import string

ipaddress = input("please input ip: ")
item = ipaddress.split('.')
true = 0
for n in {0,1,2,3}:
    m = int(item[n])
    first = int(item[n][0])
    if first == 0 or m<0 or m>255:
        print(f"{ipaddress} is Neither")
    else:
        true +=1
        if true == 4:
            print(f"{ipaddress} is IPV4")

测试3

随机生成10个验证码,验证码由3个数字和3个字母组成

import random
import string 块string.ascii_letters:
"".join(random.sample(string.digits, 3)) + "".join(random.sample(string.ascii_letters, 3))
for i in range(10):
    print("".join(random.sample(string.digits, 3)) + "".join(random.sample(string.ascii_letters, 3)))

测试4

给定一个字符串,验证是否为回文字符串,忽略大小写,只考虑字母和数字字符

import string
item = input('please input string:')
if len(item) == 0:
    print(':',True)
else:
    item = item.lower()
    cleanstr = ''
    for items in str:
        if items in string.ascii_letters +string.digits:
            cleanstr += items
    print(':', cleanstr == cleanstr[::-1])
    import string
原文链接:https://blog.csdn.net/qq_45090453/article/details/113666058
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值