文章目录
字符串
字符串分为单行字符串和多行字符串。
单行字符串以单引号或双引号作为边界。多行字符串以三引号作为边界。
print('this is a string')
print("this is a string")
print('''
this is a string.
I'm learning it.
''')
this is a string
this is a string
this is a string.
I'm learning it.
字符串的索引与切片
对字符串中某一个字符进行检索称为字符串的索引。
索引有两种方式:正向递增和反向递减。
s = '好好学习 天天向上'
print(s[0])
print(s[-1])
好
上
对字符串中某一个区间的检索称为字符串的切片
s = '好好学习 天天向上'
print(s[2:])
学习 天天向上
字符串的format方法
print('好好{} 天天{}'.format('学习','向上'))
好好学习 天天向上
前面的两个大括号{ }是槽,若没有指定参数,则分别对应.format中的对应参数。
也可以指定参数
print("好好{1},天天{0}".format('向上','学习'))
好好学习,天天向上
format方法的格式控制
大括号{ }中除了可以指定参数外,还可以包括格式控制信息。
格式控制信息用来控制参数显示时的格式。包括填充、对齐、宽度、精度、类型。
注意:前面要加冒号作为引导符号
: | 填充 | 对齐 | 宽度 | , | .精度 | 类型 |
---|---|---|---|---|---|---|
引导符号 | 用于填充的字符样式 | 左对齐、右对齐、居中 | 槽的设定输出宽度 | 数字的千位分隔符 | 浮点数小数部分的精度 | 整数类型or浮点数类型 |
填充
若参数的实际宽度大于设定值,则用参数的实际长度。若参数的实际宽度小于设定值,则按对齐指定方式对齐。默认以空格填充。
对齐
分别用<、>、^来表示左对齐、右对齐和居中对齐。
宽度
槽的设定输出宽度
s = 'python'
print('{:<25}'.format(s))
print('{:>25}'.format(s))
print('{:^25}'.format(s))
print('{:*^25}'.format(s))
python
python
python
*********python**********
精度
由小数点开头,对于浮点数,表示小数部位输出的有效位数。对于字符串,精度表示输出的最大长度。
类型
对于整数类型:b表示二进制;c表示整数对应的Unicode字符;d表示整数的十进制方式;o表示整数的八进制方式;x表示整数的十六进制方式。
对于浮点数类型:e表示输出浮点数对应的小写字母e的指数形式;E表示输出浮点数对应的大写字母E的指数形式;f输出浮点数的标准浮点形式;
print('{:.2f}'.format(3.1415926)) # 输出两位小数
print('{:x}'.format(1010)) # 输出十六进制的形式 其中英文字母小写
3.14
3f2
字符串操作符
操作符 | 描述 |
---|---|
x+y | 将两个字符串相连接 |
x*n | 将字符串x复制n次 |
x in y | 判断子串x是否在y中 |
x = 'hello world'
y = 'I love python'
print(x+y)
print(x*2)
print('hello' in x)
hello worldI love python
hello worldhello world
True
字符串处理函数
函数 | 功能 |
---|---|
len(s) | 返回字符串的长度 |
str(s) | 返回任意类型s所对应的字符串形式 |
chr(s) | 返回Unicode编码x对应的单字符 |
ord(s) | 返回单字符x表示的Unicode编码 |
hex(s) | 返回整数x对应十六进制数的小写形式字符串 |
oct(s) | 返回整数x对应八进制数的小写形式字符串 |
字符串处理方法
方法 | 描述 |
---|---|
str.upper() | 将字符串全部字符大写 |
str.lower() | 将字符串全部字符小写 |
str.split(seq=None) | 返回一个列表,由str被seq分隔的部分组成 |
str,count(sub) | 返回sub子串出现的次数 |
str.replace(old,new) | 返回字符串的副本,所有的old被替代成了new |
str.center() | 字符串居中函数 |
str.strip(chars) | 从字符串str中去掉在其左侧和右侧chars中列出的字符 |
str.join(iter) | 将iter变量的每一个元素后增加一个str字符串 |
str.lower() and str.upper()
s = 'python'
print(s.lower()) # 将字符串s小写
print(s.upper()) # 将字符串s大写
print(s.title()) # 将字符串s的首字母大写
python
PYTHON
Python
str.split(seq = None)
将字符串按照seq里的内容进行分割,将分割后的内容以列表的形式返回。
s = 'I love python'
print(s.split())
['I', 'love', 'python']
s = 'I love python'
print(s.split('o'))
['I l', 've pyth', 'n']
str.count(a)
计算字符串str中出现子串a的次数
s = 'I love python'
print(s.count('o'))
2
str.replace(old,new)
将字符串str中old子串用new子串代替
s = 'I love python'
print(s.replace('o','#'))
I l#ve pyth#n
str.center(width,fillchar)
字符串居中函数,返回长度为width的字符串,str居中,两边用fillchar填充,若str的长度大于width,则输出str。
s = 'python'
print(s.center(10,'*'))
**python**
str.strip(chars)
去掉字符串str左侧右侧出现的chars字符
s = ' python '
print(s.strip()) # 默认是空格
a = '## I love python ##'
print(a.strip('#'))
python
I love python
str.join(iter)
将字符串str添加到iter元素中
print(','.join('python'))
p,y,t,h,o,n