一、字符串的定义
a = "hello"
b = 'westos'
c = "what's up"
d = 'what\'s up' #用单引号时需要转义\
e = """
用户管理系统
1.添加用户
2.删除用户
3.显示用户
"""
输出
print(a)
print(b)
print(c)
print(d)
print(e)
print(type(e)) #查看e的类型`
二、字符串的特性
s = ‘hello’
1.索引:0,1,2,3,4索引值默认从0开始
2.切片
切片的规则:s[start?step]从start开始,到(end-1)结束,步长:step
print(s[0:3]) #从第一个字符开始,到第二个字符
print(s[0:4:2]) #从第一个字符开始,到第四个字符,每隔两个取一个
(1)显示所有字符
print(s[:])
(2)显示前三个字符
print(s[:3])
(3)字符串的逆序输出
print(s[::-1])
(4)除了第一个字符以外,其他全部输出
print(s[1:])
3.重复
print( s * 10)
4.连接
print(‘hello’ + ’ ’ + ‘world’)
5.成员操作符(判断一个字符是不是在该字符串内,在返回Ture,不在返回False)
print(‘h’ in s)
print(‘q’ in s)
三、字符串判断
1.判断字符串里面每个元素是否为某种类型
(1)isdigit:数字
(2)title:首字母大写,其余小写
(3)upper:将字符串变成大写
isupper:判断字符串是否是大写
print(‘hello’.upper())
print(‘hello’.isupper())
(4)lower:将字符串变成小写
islower:判断字符串是否是小写
(5)isalnum:判断字符串是否由字母或数字构成
print(‘hello123’.isalnum())
(6)isalpha:判断一个字符串是否为英文字母
print(‘123’.isalpha())
print(‘abc’.isalpha())
(7)isinstance:判断字符串是否是指定类型
print(isinstance(1,int))
print(isinstance(‘a’,str))
print(isinstance(1,str))
四、字符串去掉开头和结尾
(1)
s = ’ hello ’
a=s.strip()
print(a)
(2)
s = ’ hello ’
b=s.lstrip()
print(b)
(3)
s = ’ hello ’
c=s.rstrip()
print©
(4)
s = ’ \nhello ’
d=s.strip()
print(d)
(5)
s = ’ \thello ’
e=s.strip()
print(e)
(6)去掉h
s = ‘helloh’
f=s.strip(‘h’)
print(f)
(7)去掉he
s = ‘helloh’
g=s.lstrip(‘he’)
print(g)
五、字符串匹配开头和结尾
(1)endswith():以…结尾
filename = 'hello.log'
if filename.endswith('.log'):
print(filename)
else:
print('error')
(2)startswith():以…开始
url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub'
url3 = 'http://172.25.254.250/index.html'
if url3.startswith('http://'):
print('爬取该网页')
else:
print('错误网页')
六、字符串的搜索和替换
1.find找到子串,并返回最小的索引
s = 'hello world hello'
print(s.find('hello'))
print(s.find('world'))
2.rfind找到子串,并返回最大的索引值
print(s.rfind('hello'))
3.替换字符串中的所有的‘hello’为‘westos’
print(s)
print(s.replace('hello','westos'))
七、字符串的对齐
1.居中
print('学生管理系统'.center(30))
print('学生管理系统'.center(30,'*'))
print('学生管理系统'.center(30,'@'))
2、左对齐
print('学生管理系统'.ljust(30,'*'))
3、右对齐
print('学生管理系统'.rjust(30,'*'))
八、字符串的统计
print('hello'.count('l')) #几个l
print('hello'.count('ll')) #几个ll
print(len('hello')) #字符串长度
九、字符串的分离和连接
1、分离
s = '172.25.254.250'
s1 = s.split('.')
print(s1)
date = '2019-03-17'
date1 = date.split('-') #以‘-’为分隔符分割
print(date1)
2、连接
date = '2019-03-17'
date1 = date.split('-')
print(''.join(date1)) #以空格连接
print('/'.join(date1)) #以/连接
十、字符串内建函数
cmp() 根据字符串的 ASCII 码值进行比较(py3取消)
len() 返回字符串的字符数
max() and min() 返回最大或者最小的字符,(按照 ASCII 码值排列)
enumerate() 枚举对象同时列出数据和数据下标
zip() 将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
十一、练习
(1)验证回文串
(2)标识符(变量)合法性检查
编写一个检查 Python 有效标识符的小脚本,名字是 idcheck.py。
要求:Python 标识符必须以字母或下划线开头
1). 只检查长度大于等于 2 的标识符
2). 以字母或者下划线开始
3). 后面要跟字母,下划线或者或数字
(3)学生出勤记录 student-attendance-record
(4)编写一个函数来验证输入的字符串是否是有效的 IPv4 ?
1). IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(".")分割。
比如,172.16.253.1;
2). IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。