一、什么是字符串
字符串在别的语言中是一种常量,在python中是一种典型的不可变类型
字符串的具体定义方式是使用 ' '、" "、''' '''、或""" """这些符号来定义
字符串具有可以被迭代,也可以通过下标访问的特点
例如:
s1 = 'today'
s2 = "is"
s3 = '''saturday'''
s4 = """."""
二、字符串的方法
字符串的所有方法都不会改变字符串本身,而是不同方法的返回值不同
# 查看字符串类型的所有方法
print (dir (str))
输出结果:
接下来介绍一些常见的字符串对象的方法
首先定义一个初始的字符串
s = 'today is saturday.'
print ('初始值: ' + s)
输出结果:
1、|-- capitalize() 首字母大写
print ('capitalize: ', end='')
print (s.capitalize())
输出结果:
2、|-- center(width, fill_char) 居中对齐(宽度, 填充字符)
print ('center: ', end='')
print (s.center(50, '*'))
输出结果:
3、|-- count(char) 统计元素的个数
print ('count(t): ', end='')
print (s.count('t'))
输出结果:
4、|-- endswitch(char) 以xx结束,返回布尔值
print ('endswith(y): ', end='')
print (s.endswith('y'))
输出结果:
5、|-- startswitch(char) 以xx开始,返回布尔值
print ('startswith(t): ', end='')
print (s.startswith('t'))
输出结果:
6、|-- find() 从左向右检索某个字符或者字符串在该字符串中的第一个索引位置,索引不到返回-1
print ('find("day"): ', end='')
print (s.find('day'))
输出结果:
7、|-- index() 检索某个字符或者字符串在该字符串中的索引位置,索引不到就报错
print ('index("is"): ', end='')
print (s.index('is'))
输出结果:
8、|-- rfind() 逆向(从右向左查)查找元素最后一次出现的索引位置,不改变元素索引
print ('rfind("day"): ', end='')
print (s.rfind('day'))
输出结果:
9、|-- rindex() 逆向(从右向左查)查找元素最后一次出现的索引位置,不改变元素索引
print ('rindex("day"): ', end='')
print (s.rindex('day'))
输出结果:
10、|-- format() 格式化字符串
print ('{}.format(s): ', end='')
print ('{}'.format(s))
输出结果:
11、|-- join 按照特定的规则拼接字符串
ls1 = ['today','is','saturday','.']
print ('" ".join(["today","is","saturday","."]): ', end='')
print (' '.join(ls1))
输出结果:
12、|-- split(char) 按照特定的字符串分割字符串,返回列表
print ('spilt(" "): ', end='')
ls2 = s.split(' ')
print (ls2)
输出结果:
13、|-- upper() 转大写
print ('upper(): ', end='')
print (s.upper())
输出结果:
14、lower() 转小写
print ('lower(): ', end='')
print (s.lower())
输出结果:
15、|-- strip() 清除两侧空格
s3 = ' today is saturday . '
print ('strip(): ', end='')
print (s3.strip())
输出结果:
16、|-- lstrip() 清除左侧空格
print ('lstrip(): ', end='')
print (s3.lstrip())
输出结果:
17、|-- rstrip() 清除右侧空格
print ('rstrip(): ', end='')
print (s3.rstrip())
输出结果:
18、|-- title() 标题格式(每个单词首字母大写)
print ('title(): ', end='')
print (s.title())
输出结果:
19、|-- replace(old_str, new_str) 字符串元素替换
print ('replace("saturday", "sunday"): ', end='')
print (s.replace('saturday', 'sunday'))
输出结果:
20、|-- encode() 转换编码格式(将字符串转换为字节)
print ('s.encode("utf-8"): ', end='')
print (s.encode('utf-8'))
输出结果:
注意:字节对象中,有一个 decode() 方法,可以将字节转换为对应编码
s1 = s.encode('utf-8')
print ("s1.decode('utf-8'): ", end='')
print (s1.decode('utf-8'))
输出结果:
21、除此之外,字符串类型还有一系列用于判断的方法,使用方法同上,可以稍作了解。
例如:|-- istitle() 判断字符串是否符合title方法(即每个单词首字母大写),返回布尔值
|-- islower() 判断是否符合lower(小写),返回布尔值
|-- isupper() 判断是否大写
|-- isalnum() 判断是否有效字符(是否数字和字母组成)
|-- isalpha() 判断是否全部由字母组成
|-- isaldigit() 判断是否全部由数字组成