字符串

字符串

1.字符串的表示方法

单引号

双引号

三引号

一般来嵌套使用

a = 'hello'
b = "word"
c = """hahahhah"""

# 嵌套的使用
>>> print("小明说:‘昨天去happy了!’")
小明说:‘昨天去happy了!’

>>> print("I'am xiaoming!")
I'am xiaoming!

>>> print("I'am xiaoming!")
I'am xiaoming!

# 字符转义
>>> print('I\'am xiaoming!')
I'am xiaoming!

1.1 转义字符

\ 转换为普通字符

\n 换行

\t table

\s

\ \ 普通的 \

r 原生字符串

# 字符转义
>>> print('I\'am xiaoming!')
I'am xiaoming!

# \n 换行
>>> print("hello te\nacher!")
hello te
acher!

# \t 制表符
>>> print("hello \tenacher!")
hello   enacher!

# \\ 表示原生字符串
>>> print("hello \\teacher!")
hello \teacher!

# r原生字符串
>>> print(r"hello \\\\n\teacher!")
hello \\\\n\teacher!

2.下标和切片

下标: 表示第几个数据,一般从0开始计算。通过下标来修改指定位置的数据。

可迭代对象: 可以使用下标,str 、list、tuple、dict、set、range都可以进行遍历。

字符串、元组、列表都可以使用下标来获取数据;字符串是不可更改类型,操作都不会更改原来的内容。

切片: 从字符串中复制一段指定的内容,生成一个新的字符串。

[start,end,step]

start 开始

end 结尾

step 步长,默认为1,步长不能为0,可以为负数。

# 获取指定下标字母
>>> word = 'zhangsan'
>>> word[4]
'g'

# 切片,不包含结尾。
>>> words = 'abcdefghijklmn'
>>> words[:2]     # 从开始截取
'ab'
>>> words[0:2]    # 不包含结尾
'ab'
>>> words[:3]
'abc'
>>> words[0:3]
'abc'

# 某个位置开始到结尾
>>> words = 'abcdefghijklmn'
>>> words[3:]
'defghijklmn'
>>> words[3:1:-1]    # 第三个开始到第一个,从右向左,取不到结尾
'dc'
>>> words[::]    # 从头到尾复制
'abcdefghijklmn'

>>> words[::-1]    # 倒序复制
'nmlkjihgfedcba'

>>> words[-6:-3]   # 倒数第六个到倒数第4个,取不到结尾。
'ijk'

3.字符常用操作方法

3.1 find index rfind rindex

找下标最小的索引

len() # 获取字符串长度

find index rfind rindex # 查找内容相关方法,可以获取指定字符的下标。

>>> x = 'abcdefghijklmn'
>>> len(x)
14
>>> x.find('f')     # 返回字符串的下标
5
>>> x.index('f')
5

>>> x.index('z')    # 如果字符串中没有会报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> x.find('z')    # 如果字符串中没有会返回-1
-1

>>> x.find('z',4,12)    #在下标4 - 12中去找
-1

找下标最大的索引

rfind()

rindex()

>>> x = 'abcdefghijkllmn'
>>> rfind("l")
>>> x.rfind("l")
12
>>> x.find("l")
11

>>> x.rindex("l")
12
>>> x.index("l")
11

3.2 startswitch endswitch

>>> x ='hello word'
>>> x.startswith("he")   # 判断以那个字符开始,返回布尔值。
True

>>> x.endswith("rd")    # 判断以哪个字符结尾。
True

3.3 isalpha

>>> word = 'hello'
>>> word.isalpha()    # 判断字符串是否是纯字母
True

>>> word = 'hello word'    # 因为有空格了
>>> word.isalpha()
False

3.4 isdigit

# 只要是出现不是0-9组成的数字都是False
>>> num = '123'
>>> num.isdigit()
True
>>> num = '-123'
>>> num.isdigit()
False
>>> num = '3.14'
>>> num.isdigit()
False
>>> num = '123'
>>> num.isdigit()
True
>>> num = '-123'
>>> num.isdigit()
False
>>> num = '3.14'
>>> num.isdigit()
False

3.5 isalnum

# 只有数字和字母组成的字符,否则就是False
>>> num = '123abc'
>>> num.isalnum()
True
>>> num = '123 abc'
>>> num.isalnum()
False

3.6 isspace

# 只有空格组成的字符串,否则返回False
>>> word = '   '
>>> word.isspace()
True

>>> words = ' 123'
>>> words.isspace()
False

3.7 count计数

# 统计字符串中,某个字符出现的次数
>>> words = 'aabbccdffefefefgggg'
>>> words.count('a')
2
>>> words = 'aabbccdffecfefefgggg'
>>> words.count('c')
3
>>> words.count('c',0,6)    # 在前六位中c出现的次数
2
>>> words.count('e',-7,-1)    # 倒置索引范围中取值
1

3.8 replace替换

>>> words = '今天的天气真的好!'
>>> words.replace('天','晚')    # 默认全部替换
'今晚的晚气真的好!'
>>> words.replace('天','晚',1)    # 指定替换的次数
'今晚的天气真的好!'

内容分割

3.9 split rsplit splitlines

# 使用指定分隔符把字符生成列表
>>> words = 'sheldon-john-tom-jimi-frank'
>>> words.split('-')
['sheldon', 'john', 'tom', 'jimi', 'frank']
>>> words.split('-',2)    # 最多分成两份
['sheldon', 'john', 'tom-jimi-frank']
>>> words.split('-',3)  # 最多分成三份,长度为3+1
['sheldon', 'john', 'tom', 'jimi-frank']

>>> len(words.split("-",3))    # 长度
4
>>> words = 'sheldon-wangming-frank-john-tom'
>>> words.rsplit("-")
['sheldon', 'wangming', 'frank', 'john', 'tom']
>>> words.rsplit("-",2)
['sheldon-wangming-frank', 'john', 'tom']
>>> words = '\nhello \nword!'    # 以换行为分隔符创建列表。
>>> words.splitlines()
['', 'hello ', 'word!']

3.10 partition rpartition

>>> name = '激情与速度.mp4'    
>>> name.partition(".")    # 指定分隔符,把字符串分成三分的,并创建列表
('激情与速度', '.', 'mp4')
>>> name = '2012.1.12 激情与速度.mp4'
>>> name.rpartition(".")    # 从右边开始分
('2012.1.12 激情与速度', '.', 'mp4')

修改大小写

3.11 capitalize

>>> words = "mr.smith,how are you!"
>>> words.capitalize()    # 只针对字母,中文不支持
'Mr.smith,how are you!'

3.12 title

>>> content = 'lomeou and juelyer'
>>> content.title()    # 字符串穿每个字母前单词大写,题目
'Lomeou And Juelyer'

3.13 lower upper

>>> words = 'ABCdefGhijkLMN'
>>> words.upper()    # 所有单词大写
'ABCDEFGHIJKLMN'
>>> words.lower()    # 所有单词小写
'abcdefghijklmn'

# 应用
while True:
    comtent  = input("输入exit退出:")
    print(comtent.lower())    # 无论输入大小写都判断为小写。
    if comtent.lower() == 'exit':
        break

3.14 ljust rjjust

>>> words = 'hello'
>>> words.ljust(10,'+')    # 长度为10向左靠齐,长度不足用+代替,默认使用空格填充。
'hello+++++'
# 长度为10向左靠齐,长度不足用+代替,默认使用空格填充。
>>> words.rjust(10,'+')
'+++++hello'

>>> words.center(10)    # 原本字符串长度,如果超出了指定长度就会失效。
'aaaaavvvvvvvvbbbbbb'
>>> words.ljust(10)
'aaaaavvvvvvvvbbbbbb'
>>> words.rjust(10)
'aaaaavvvvvvvvbbbbbb'

3.15 center

>>> words.center(10,'+')    # 指定长度居中对齐,默认空格填充
'++hello+++'

3.16 strip lstrip rstrip

>>> words= '****aaa****'
>>> words.lstrip("*")    # 去除字符串左边的指定字符,不指定默认去除空格。
'aaa****'
>>> words.rstrip("*")    # 去除字符串右边边的指定字符,不指定默认去除空格。
'****aaa'
>>> words.strip("*")    # 去除字符串两边的指定字符,不指定默认去除空格。
'aaa'

3.17 jion

>>> txt = '-'
>>> words = ['a','b','c','d']
>>> txt.join(words)    # 用于快速把一个迭代对象,生成为字符串,并可以指定字符。
'a-b-c-d'

4.字符的编码和编码集

4.1 字符集

​ 计算机只能处理理数字(其实就是数字0和数字1),如果要处理理⽂文本,就必须先把⽂文本转换为数字才能处理。最早的计算机在设计时采⽤用8个比特(bit)作为一个字节(byte),所以,一个字节能表示的最⼤大的整数就是255(⼆二进制11111111=⼗十进制255), 0 - 255被⽤用来表示⼤大⼩小写英⽂文字⺟母、数字和一些符号,这个编码表被称为ASCII编码。ASCII码表使⽤用7位二进制表示一个字符,它的区间范围时0~127,一共只能表示128个字符,仅能⽀支持英语。随着计算机科学的发展,⻄西欧语⾔言、希腊语、泰语、阿拉伯语、希伯来语等语⾔言的字符也被添加到码表中,形成了了一个新的码表ISO8859-1(又被称为Latin1)码表。 ISO8859-1使⽤用8位二进制表示一个字符串,完全
兼容ASCII码表。
Unicode(统一码、万国码、单一码)是计算机科学领域里一项业界标准,包括字符集、编码⽅方案等。Unicode 是为了了解决传统的字符编码⽅方案的局限⽽而产生的,它为每种语言中的每个字符设定了了统⼀并且唯⼀的二进制编码,以满足跨语言、跨平台进行文本转换、处理的要求。

4.2 字符和编码的互相转换

使用ord和chr方法

# 查看字母a在字符串中的编号
>>> ord('a')
97

>>> ord('a')
97
# 查看ascii表65对应的字母是什么
>>> chr(65)
'A'

4.3 编码规则

定义了编码在存储或者打开在读取或者写入二进制数据的规则。

使用Unicode为每种语言的每个字符都设定了唯⼀的二进制编码,但是它还是存在一定的问题。
例如,汉字 “你” 转换成为⼀一个字符结果是 0x4f60 ,转换成为二进制就是 01001111 01100000 ,此时就有两个问题:

  1. 1001111 01100000 到底是一个汉字 “你” ,还是两个 Latin1 字符?

  2. 如果Unicode进⾏行行了了规定,每个字符都使⽤用n个八位来表示,对于Latin1字符来说,又会浪费很多存储空间。

为了解决这个问题,就出现了了一些编码规则,按照一定的编码规则对Unicode数字进行计算,得出新的编码。在中国常⽤用的字符编码有 GBK , Big5 和 utf8 这

GBK 规定一个字符占用两位。

uf8 规定一个字符占用三位。

三种编码规则。 使用字符串的encode⽅方法,可以将字符串串按照指定的编码格式转换称为二进制;使用decode⽅方法,可以将⼀个二进制数据按照指定的编码格式转换成为字符串。

# 查看字符的二进制编码
>>> a = '你'.encode("gbk")
>>> a
b'\xc4\xe3'

# 解码查看
>>> print(0xc4e3)
50403
>>> bin(50403)
'0b1100010011100011'
>>> bin(0xc4e3)
'0b1100010011100011'

# 根据二进制进行还原
>>> hex(0b1100010011100011)
'0xc4e3'
>>> a = b'\xc4\xe3'
>>> a.decode("gbk")
'你'

# 字符乱码的情况。
>>> a = '你好'
>>> a.encode("utf8")
# utf8编码规定一个字符是三位
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> b = b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> b.decode("gbk")
# gbk 规定一个字符是两位,所以使用前两位解码出来是这样的。
'浣犲ソ'
>>> c =  b'\xe4\xbd'
>>> c.decode("gbk")
'浣'

5.in 和not in的使用

查看一个字符是否在一个可迭代的对象中。

# 返回的是布尔值
>>> a= 'hello'
>>> "l" in a
True
>>> "y" in a
False

# not in判断一个字符或者元素不在一个可迭代对象中。
>>> a = ["tom", "jerry", "honey"]
>>> "tank" not in a
True
>>> "tom" not in a
False

其它方法

# 判断l是否在hello中
for i in "hello":
    if "l" == i:
        print("hello中有l")
        break
else:
    print('meiyou')
    
w = input("请输入一个字母:")
if "hello".find(w) != -1:
    print("包含你输入的字母!")
else:
    print("没有你包含的字母!")

6.字符串格式化方法

使用%占位符来表示格式化一个字符串

%d 表示整数

%nd 表示占用几位

%0nd 表示显示位数不足用0来填充

%-nd 表示显示位数在后面添加

%s 表示字符

%f 表示浮点数会四舍五入

%.2f 取小数后两位

%x 输出十六进制小写

%X 输出十六进制大写

%% 打印百分号

>>> print("我的名字叫%s,我今年%d,我来自%s" %("xiaodong",23,"chongqing"))
我的名字叫xiaodong,我今年23,我来自chongqing

>>> print("我的名字叫%s" %"晓东")
我的名字叫晓东

>>> print("圆周率%f"%3.14159)
圆周率3.141590

>>> print("我的年龄有%4d" %23)
我的年龄有  23
>>> print("我的年龄有%04d" %23)
我的年龄有0023
>>> print("我的年龄有%-04d哈哈哈" %23)
我的年龄有23  哈哈哈

>>> print("圆周率%.2f" %pi)
圆周率3.14

>>> print("十六进制%x" %255)
十六进制ff
>>> print("十六进制%X" %255)
十六进制FF

format 方法

替换{}中的内容

# 最简单的使用方法
>>> print("我叫{},我来自{},我今年{}".format("晓东", "重庆", 23))
我叫晓东,我来自重庆,我今年23

# 根据位置找参数
>>> print("我叫{2},我来自{0},我今年{1}".format("重庆", 23, "晓东"))
我叫晓东,我来自重庆,我今年23

# 使用固定参数的方式
>>> print("我叫{name},我来自{addres},我今年{age}".format(addres="重庆", age=23, name ="晓东"))
我叫晓东,我来自重庆,我今年23

# 混合使用
>>> print("我叫{name},我来自{1},我今年{0}".format(23, "重庆", name = "晓东"))
我叫晓东,我来自重庆,我今年23

# 和列表配合使用的情况
>>> names = ["tom", "jerry", "spak"]
>>> print("猫的名字叫{},老鼠的名字叫{},狗的名字叫{}".format(*names))
猫的名字叫tom,老鼠的名字叫jerry,狗的名字叫spak

# 和字典配合使用
>>> info = {"name": "tom", "age": 23, "from": "USA"}
>>> print("我叫{name},我来自{from},我今年{age}".format(**info))
我叫tom,我来自USA,我今年23
posted @ 2022-05-22 16:33  Gshelldon  阅读(120)  评论(0编辑  收藏  举报