文章目录
Python内置的数据类型简介
- 可变数据类型: list, set, dict
- 不可变数据类型: 数值类型,tuple, str
1. 字符串str
<创建>
- 单引号引起来:
name = 'westos'
- 双引号引起来:
name = "westos"
- 三引号引起来: 三引号代表字符串, 也可以作为代码的块注释
<基本特性>
- 连接(+)重复(*)
name = 'westos'
print('hello ' + name)
# 1元 + 1分 = 1元 + 0.01元 = 1.01元
print('hello' + str(1))
print("*" * 30 + '学生管理系统' + '*' * 30)
- 成员(in, not in)
s = 'hello westos'
print('westos' in s) # True
print('westos' not in s) # False
print('x' in s) # False
- 索引: 正向索引和反向索引
s = 'WESTOS'
print(s[0]) # 'W'
print(s[3]) # 'T'
print(s[-3]) # 'T'
- 切片:s[start : end : step]
s = '012345'
print(s[:3]) # s[:n]获取前n个字符
print(s[2:]) # s[n:]获取除了前n个字符的字符串信息
print(s[::-1]) # 字符串倒序
- for循环访问
s = 'westos'
count = 0
for item in s:
count += 1
print(f"第{count}个字符:{item}")
判断回文字符串
s = input('输入字符串:')
result = "回文字符串" if s == s[::-1] else "不是回文字符串"
print(s + "是" + result)
<常用方法>
- 判断类型(isdigit, isupper, islower, isalpha, isalnum)
- 转换类型:(lower, upper, title)
- 开头和结尾的判断(startswith, endswith)
- 数据清洗(strip, lstrip, rstrip, replace)
- 分割和拼接(split,
'172.25.254.100'.split(".")
, join) - 位置调整(center)
1.类型判断
s = 'HelloWESTOS'
print(s.isalnum()) # True
print(s.isdigit()) # Flase
print(s.isupper()) # False
2.类型的转换
print('hello'.upper()) # HELLO
print('HellO'.lower()) # hello
print('HellO WOrld'.title()) # Hello World
print('HellO WOrld'.capitalize()) # Hello world
print('HellO WOrld'.swapcase()) # hELLo woRLD
# 需求: 用户输入Y或者y都继续继续代码
# yum install httpd
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(" ", )
"""
print(" hello ".strip()) # 'hello'
print(" hello ".lstrip()) # 'hello '
print(" hello ".rstrip()) # ' hello'
print(" hel lo ".replace(" ", "")) # 'hello'
5.字符串的位置调整
# 中间对齐,一共10个字符,可指定字符补齐
print("学生管理系统".center(10)) # ' 学生管理系统 '
print("学生管理系统".center(10, "*")) # '**学生管理系统**'
print("学生管理系统".center(10, "-")) # '--学生管理系统--'
# 左对齐,右对齐
print("学生管理系统".ljust(10, "-")) # '学生管理系统----'
print("学生管理系统".rjust(10, "-")) # '----学生管理系统'
6.字符串的搜索和统计
s = "hello westos"
print(s.find("llo")) # 2
print(s.index("llo")) # 2
print(s.find("xxx")) # -1
print(s.index("xxx"))
报错:Traceback (most recent call last):
File "D:\Python Learning\day02\07_字符串的搜索和统计.py", line 6, in <module>
print(s.index("xxx"))
ValueError: substring not found
# find如果找到子串, 则返回子串开始的索引位置。 否则返回-1
# index如果找到子串,则返回子串开始的索引位置。否则报错(抛出异常).
print(s.count("xxx")) # 0
print(s.count("l")) # 2