Python学习笔记7——字符串

1、字符串的驻留机制
字符串连接操作中,join()比+效率高很多

#强制驻留(可节省空间)
import sys
a = 'abc%'
b = 'abc%'
print(a is b)   #False
a = sys.intern(b)
print(a is b)    #True
#以上的结果在pycharm都会显示为True,因为pycharm会进行优化,但在python idle中是会显示不同的结果

2、字符串的查询操作
(1)index()方法 查找子串substr第一次出现的位置,如果查找的子串不存在,则抛出ValueError
(2)rindex()方法 查找子串substr最后一次出现的位置,如果查找的子串不存在,则抛出ValueError
(3)find()方法 查找子串substr第一次出现的位置,如果查找的子串不存在,则输出-1
(4)rfind()方法 查找子串substr最后一次出现的位置,如果查找的子串不存在,则输出-1

s = 'hello,hello'
print(s.index('lo'))
print(s.rindex('lo'))
print(s.find('lo'))
print(s.rfind('lo'))

#print(s.index('k'))   #报错
print(s.find('k'))     #不会报错
#因此建议用find()或者rfind()来查找

输出结果:
3
9
3
9
-1

用index和rindex查找不存在的子串时,会报错;而find和rfind不会报错,因此建议用find和rfind来查找

3、字符串的大小写转换操作
(1)upper()方法 把字符串中所有字符都转成大写字母
(2)lower()方法 把字符串中所有字符都转成小写字母
(3)swapcase()方法 把字符串中所有大写字母转成小写字母,把所有小写字母转成大写字母
(4)capitalize()方法 把第一个字符转换成大写,其余转换成小写 (一句话的第一个字母)
(5)title()方法 把每个单词的第一个字符转换为大写,把每个单词的剩余字符转换为小写 (每个单词的第一个字母)

s = "hello,python"
a = s.upper()
print(s,id(s))     #原来的s是不会改变的
print(a,id(a))     #字符串是不可变序列,转换成大写之后会产生一个新的字符串对象
b = s.lower()
print(s,id(s))
print(b,id(b))   #转换之后,会产生一个新的字符串对象 虽然转换为小写之后,字符串的内容是一样的

输出结果:
hello,python 1781137041712
HELLO,PYTHON 1781137041328
hello,python 1781137041712
hello,python 1781137043184

4、字符串内容对齐操作
(1)center() 居中对齐,第一个参数指定宽度,第二个参数指定填充符,第二个参数默认是空格,如果设置的宽度小于字符串实际宽度,则返回原字符串

#center() 居中对齐,第一个参数指定宽度,第二个参数指定填充符,第二个参数默认是空格,如果设置的宽度小于字符串实际宽度,则返回原字符串
s = "hello,python"
print(s.center(20,'*'))

输出结果:
####hello,python####

(2)ljust() 左对齐,第一个参数指定宽度,第二个参数指定填充符,第二个参数默认是空格,如果设置的宽度小于字符串实际宽度,则返回原字符串

#ljust()  左对齐,第一个参数指定宽度,第二个参数指定填充符,第二个参数默认是空格,如果设置的宽度小于字符串实际宽度,则返回原字符串
print(s.ljust(20,'#'))
print(s.ljust(10,'#'))    #小于实际宽度,返回原字符
print(s.ljust(20))    #后面默认是空格

输出结果:
hello,python########
hello,python
hello,python

(3)rjust() 右对齐,第一个参数指定宽度,第二个参数指定填充符,第二个参数默认是空格,如果设置的宽度小于字符串实际宽度,则返回原字符串

#rjust()  右对齐,第一个参数指定宽度,第二个参数指定填充符,第二个参数默认是空格,如果设置的宽度小于字符串实际宽度,则返回原字符串
print(s.rjust(20,'#'))
print(s.rjust(10,'#'))    #小于实际宽度,返回原字符
print(s.rjust(20))    #前面默认是空格

输出结果:
########hello,python
hello,python
hello,python (这里显示有点错误)

(4)zfill() 右对齐,左边用0填充,该方法只接收一个参数,用于指定字符串的宽度,如果设置的宽度小于字符串实际宽度,则返回原字符串

#zfill()  右对齐,左边用0填充,该方法只接收一个参数,用于指定字符串的宽度,如果设置的宽度小于字符串实际宽度,则返回原字符串
print(s.zfill(20))
print(s.zfill(10))
print('-8910'.zfill(8))   #注意这里的0是添加到-号之后

输出结果:
00000000hello,python
hello,python
-0008910

5、字符串的劈分
(1)split()
①从字符串的左边开始劈分,默认的劈分字符是空格字符串,返回的值都是一个列表
②可以通过参数sep指定劈分字符串的劈分符
③通过参数maxsplit()指定劈分字符串时的最大劈分次数,在经过最大次劈分之后,剩余的子串会单独作为一部分

s = "hello world python"
lst = s.split()
print(lst)
s1 = "hello|world|python"
print(s1.split(sep='|'))
print(s1.split(sep='|',maxsplit=1))   #分出一段后,剩余的子串为一段

输出结果:
[‘hello’, ‘world’, ‘python’]
[‘hello’, ‘world’, ‘python’]
[‘hello’, ‘world|python’]

(2)rsplit()
从字符串的右边开始劈分,其余的同split()

print(s.rsplit())
print(s1.rsplit(sep='|'))
print(s1.rsplit(sep='|',maxsplit=1))   #只有这一句的结果有所不同,从右开始劈分,最大劈分次数为1

输出结果:
[‘hello’, ‘world’, ‘python’]
[‘hello’, ‘world’, ‘python’]
[‘hello|world’, ‘python’]

6、字符串判断的方法
(1)isidentifier()判断指定的字符串是不是合法的标识符(只由数字、字母、下划线组成)

#isidentifier()判断指定的字符串是不是合法的标识符(只由数字、字母、下划线组成)
s = 'hello,world'
print('1',s.isidentifier())   #,不是
print('2','hello'.isidentifier())
print('3','张三_'.isidentifier())
print('4','张三_123'.isidentifier())

输出结果:
1 False
2 True
3 True
4 True

(2)isspace()判断指定的字符串是否全部由空白字符组成(回车、换行、水平制表符)

print('5','\t'.isspace())

输出结果:
5 True

(3)isalpha()判断指定的字符串是否全部由字母组成

print('6','abc'.isalpha())
print('7','张三'.isalpha())   #True

输出结果:
6 True
7 True

(4)isdecimal()判断指定字符串是否全部由十进制的数字组成

print('8','123'.isdecimal())
print('9','123四'.isdecimal())
print('10','ⅠⅡⅢ'.isdecimal())

输出结果:
8 True
9 False
10 False

(5)isnumeric()判断指定字符串是否全部由数字组成

print('11','123'.isnumeric())
print('12','123四'.isnumeric())   #True
print('13','ⅠⅡⅢ'.isnumeric())   #True

输出结果:
11 True
12 True
13 True

(6)isalnum()判断指定字符是否全部由字母和数字组成

print('14','张三123'.isalnum())    #True

输出结果:
14 True

7、字符串的常用操作——替换与合并
(1)replace() 字符串替换
第1个参数指定被替换的子串,第2个参数指定替换子串的字符串,该方法返回替换后得到的字符串,替换前的字符串不发生改变,调用该方法可以通过第3个参数指定最大替换次数

s = "hello,python"
print(s.replace('python','java'))
s1 = "hello,python,python,python"
print(s1.replace('python','java',2))

输出结果:
hello,java
hello,java,java,python

(2)join() 字符串合并
将列表或元组中的字符串合并成一个字符串

#将列表或元组中的字符串合并成一个字符串
lst = ['hello','python','java']
print('|'.join(lst))
print(''.join(lst))

t = ('hello','python','java')
print(''.join(t))

print('*'.join('python'))

输出结果:
hello|python|java
hellopythonjava
hellopythonjava
pytho*n

8、字符串的比较操作
8.1
运算符:>,>=,<,<=,==,!=
比较规则:首先比较两个字符串中的第一个字符,如果相等则继续比较下一个字符,依次比较下去,直到两个字符串中的字符不相等时,其比较结果就是两个字符串的比较结果,两个字符串中的所有后续字符将不再被比较。
比较原理:两_上字符进行比较时,比较的是其ordinal value(原始值),调用内置函数ord可以得到指定字符的ordinal value。与内置函数ord对应的是内置函数chr,调用内置函数chr时指定ordinal value可以得到其对应的字符
(就是ord()可以得到原始值,chr()可以得到对应字符)

print('apple'>'app')
print('apple'>'banana')
print(ord('a'),ord('b'))
print(chr(97),chr(98))
print(ord('姜'))
print(chr(23004))

输出结果:
True
False
97 98
a b
23004

8.2 ==与is的区别
==比较的是value是否相等
is比较的是id是否相等

 # ==比较的是value是否相等
# is比较的是id是否相等
a = b = 'python'
c = 'python'
print(a==b)
print(a==c)
print(a is b)
print(a is c)

输出结果:
True
True
True
True

9、字符串的切片操作
完整写法[start:stop:step]

#完整写法[start:stop:step]
s = 'hello,python'
s1 = s[:5]    #由于没有指定起始位置,所以从0开始切
s2 = s[6:]    #由于没有指定结束位置,所以切到字符串的最后一个元素
s3 = '!'
print(s1)
print(s2)
print(s1+s3+s2)
print(s[1:5:1])   #从1开始,不包含5,步长为1
print(s[::-1])   #倒过来  默认从最后一个字符开始,到第一个字符结束,因为步长为负数
print(s[-6:])

输出结果:
hello
python
hello!python
ello
nohtyp,olleh
python

10、格式化字符串(模板)
(1)第一种方法:%作占位符

name = '张三'
age = 24
print("我叫%s,今年%d岁" % (name,age))

输出结果:
我叫张三,今年24岁

(2)第二种方法:{}作占位符

print("我叫{0},今年{1}岁".format(name,age))

输出结果:
我叫张三,今年24岁

(3)第三种方法:f

print(f"我叫{name},今年{age}岁")

输出结果:
我叫张三,今年24岁

对于%

#对于%
print("%10d" % 99)    #这个10表示的是宽度
print("%.3f" % 3.1415926)   #.3表示小数点后三位
#可以同时表示宽度和精度
print("%10.3f" % 3.1415946)   #一共总宽度为10,保留小数点后三位

输出结果:
99 (右对齐,这里显示有问题)
3.142
3.142 (右对齐,这里显示有问题)

对于{}

print("{0:.3} {1}".format(3.1415926,6))   #.3表示的是一共是3位数   0代表的是占位符的顺序,也可以省略不写
print("{:.3} {}".format(3.1415926,6))    #占位符的序号可以都不写
#print("{0:.3} {}".format(3.1415926,6))  #有的写有的不写会报错 ValueError: cannot switch from manual field specification to automatic field numbering
print("{0:.3f}".format(3.1415926))  #.3f表示的才是小数点后3位

print("{:10.3f}".format(3.1415926))   #同时设置宽度和精度,10.3表示宽度是10,一共有3位小数

输出结果:
3.14 6
3.14 6
3.142
3.142(右对齐宽度为10,这里显示有问题)

注意{}的.3表示一共有3位数,.3f表示的才是小数点后3位数

11、字符串的编码与解码
编码:将字符串转换为二进制数据(bytes)
解码:将bytes类型的数据转换成字符串类型

s = '天涯共此时'
#编码
print(s.encode(encoding='GBK'))  #在GBK这种编码格式中,一个中文占两个字节
print(s.encode(encoding='utf-8'))  #在utf-8这种编码格式中,一个中文占三个字节

输出结果:
b’\xcc\xec\xd1\xc4\xb9\xb2\xb4\xcb\xca\xb1’
b’\xe5\xa4\xa9\xe6\xb6\xaf\xe5\x85\xb1\xe6\xad\xa4\xe6\x97\xb6’

#解码
#byte代表就是一个二进制数据(字节类型的数据)
byte = s.encode(encoding='GBK')
print(byte.decode(encoding='GBK'))    #GBK的只能用GBK去解
#print(byte.decode(encoding='utf-8'))   #会报错,因为GBK的只能用GBK去解

输出结果:
天涯共此时

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值