Python基础【第五篇】:基础数据类型(字符型)
String(字符串)
字符串的形式
在python中字符串可以用’ ‘(单引号),“ ”(双引号),和’‘’ ‘’‘(三个单引号)。
string1 = 'james' string2 = '''kobe''' string3 = "jordan" print(string1,string2,string3)
python中访问字符串的方法
Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。
Python 访问子字符串,可以使用方括号来截取字符串
string = 'abcdefg' #1.string[0:n]表示,从从第一个元素到第n个元素 print("前四个元素:",string[0:4]) #2.string[a:b]表示从第a+1个元素到第b个元素 print("第二个元素到第三个元素:",string[1:3]) #3.string[:n]表示前n个元素 print("前三个元素:",string[:3]) #4.string[n:]表示从第n+1个元素到最后 print("第四个元素到最后一个元素:",string[3:]) #5.string[:]等价于字符串本身 print("所有的元素:",string[:]) #6.string[-n:]表示从后截取的n个元素组成的字符串 print("string[-2:]:",string[-2:]) #7.string[:-n]表示从后去掉n个元素后的字符串 print("string[:-2]:",string[:-2]) #8.string[a:b]若a>b,默认输出空 print("string[3:2]:",string[3:2]) #9.string[::n]表示从头到尾步长为n形成的字符串 print("string[::2]:",string[::2]) #10.string[::-n]表示从尾到头步长为n形成的字符串 print("string[::-2]:",string[::-2])
输出:
前四个元素: abcd 第二个元素到第三个元素: bc 前三个元素: abc 第四个元素到最后一个元素: defg 所有的元素: abcdefg string[-2:]: fg string[:-2]: abcde string[3:2]: string[::2]: aceg string[::-2]: geca
索引值以 0 为开始值,-1 为从末尾的开始位置。
操作符 ’ :‘ 代表了所以的意思。
怎么看截取的字符串?
- 一看数字:假如是正数就从开头数,假如是负数就从结尾数。
- 二看结构:包头不包尾。[a:b],包含下标为a的字符,但不包括下标为b的字符。
- 三看方向:我们需要看’:‘在什么地方,如果在左边就往左边走,在右边就往右边走。
比如:
string = 'abcdefg' print("string[:2]:",string[:2]) #一看数字,是正数2,则从开头数到下标2的位置,是字符’c‘; #二看结构,2在尾部,所以不包含字符’c‘; #三看方向,’:‘在左边,则往左走,所以截取的字符串为从下标为2的 #字符’c‘且不包含’c‘开始,往左所有的字符:’ab‘
再有:
string = 'abcdefg' print("string[-2:]:",string[-2:]) #一看数字,是负数-2,则从结尾数到下标-2的位置,是字符’f‘; #二看结构,-2在头部,所以包含字符’f‘; #三看方向,’:‘在右边,则往右走,所以截取的字符串为从下标为-2的 #字符’f‘且包含’f‘开始,往右所有的字符:’fg‘
字符串的操作
‘+’ :拼接两个字符串
’*‘ :复制字符串 >>>a='hello' >>>a*2 >>>’hellohello‘
[] :通过索引获取字符串中的字符
in :判断一个字符串是否包含在给定字符串当中
not in :与in相反
r/R :原始字符串 - 原始字符串: 原始字符串除在字符串的第一个引号前加上字母r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。
string1 = "helloworld" string2 = "hello" string3 = "world" string = string2 + string3 print("拼接后的字符串:",string) print("string1*2:",string1*2) print("string1[1]:",string1[1]) print("string2是否包含于string1:",string2 in string1) print("string3是否不包含于string1:",string3 not in string1) original1 = r"orig" original2 = R"inal" print("原始字符:",original1 + original2)
此实例输出:
拼接后的字符串: helloworld string1*2: helloworldhelloworld string1[1]: e string2是否包含于string1: True string3是否不包含于string1: False 原始字符: original
Python中字符格式化
Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。
在 Python 中,字符串格式化使用与 C 中 sprintf 函数一样的语法。
符 号 | 描述 |
---|---|
%c | 格式化字符及其ASCII码 |
%s | 格式化字符串 |
%d | 格式化整数 |
%u | 格式化无符号整型 |
%o | 格式化无符号八进制数 |
%x | 格式化无符号十六进制数 |
%X | 格式化无符号十六进制数(大写) |
%f | 格式化浮点数字,可指定小数点后的精度 |
%e | 用科学计数法格式化浮点数 |
%E | 作用同%e,用科学计数法格式化浮点数 |
%g | %f和%e的简写 |
%G | %f 和 %E 的简写 |
%p | 用十六进制数格式化变量的地址 |
格式化操作符的辅助命令
Python2.6 开始,新增了一种格式化字符串的函数 str.format()方法,它增强了字符串格式化的功能,在本文将会讲到。
下面来演示格式化操作符的效果:
符号 | 功能 |
---|---|
. | 定义宽度或者小数点精度 |
- | 用做左对齐 |
+ | 在正数前面显示加号( + ) |
<sp> | 在正数前面显示空格 |
# | 在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X') |
0 | 显示的数字前面填充'0'而不是默认的空格 |
% | '%%'输出一个单一的'%' |
(var) | 映射变量(字典参数) |
m.n. | m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话) |
name = "kobe" age = 38 points = 33643 field_average = 24.9 highest = 81 print('''\t%s是历史上最伟大的篮球运动员之一。\n他%6.d岁从NBA退役,场均可以拿到%-10.5f分,生涯总得分为%.5e,排名历史第三。\n其中一次与猛龙的比赛中拿到了其生涯最高分%010u分,写成八进制为%o分,写成十六进制为%#x分'''%(name,age,field_average,points,highest,highest,highest))
输出:
kobe是历史上最伟大的篮球运动员之一。 他 38岁从NBA退役,场均可以拿到24.90000 分,生涯总得分为3.36430e+04,排名历史第三。 其中一次与猛龙的比赛中拿到了其生涯最高分0000000081分, 写成八进制为121分,写成十六进制为0x51分
结果解释:
- %s格式为字符串
- %6.d格式为整数,且总长度为6个,用空格填补
- %-10.5f格式为浮点数,且总长度为10,小数点后长度为5,' - '代表左对齐
- %.5e代表使用科学计数法表示,且小数点后长度为5
- %010u格式为无符号整数,且总长度为10,数字前用0填充而不是空格
- %o格式为八进制表示;%#o用十六进制表示,且在十六进制数前显示’ox‘
关于上例的三引号作用解释’‘’ ‘’‘
python三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。上例中之所以\n,\t可以起到作用,就是三引号的功能。三引号还可以起到注释的作用。
print("""三引号使[\n] ,以及[\t]等一些特殊字符发挥了作用""") ''' 这是三引号的多行注释 '''
输出:
三引号使[
] ,以及[ ]等一些特殊字符发挥了作用
字符串的存储
在Python2中,普通字符串是以8位ASCII码进行存储的,而Unicode字符串则存储为16位unicode字符串,这样能够表示更多的字符集。使用的语法是在字符串前面加上前缀 u。
在Python3中,所有的字符串都是Unicode字符串。
python中字符串的内建函数
- capitalize 该方法返回一个首字母大写,且其他为小写的字符串。
str = 'hello world' print(str.capitalize()) #输出 Hello world
- center(width,fillchar) width是字符串的总宽度,fillchar是填充字符。返回一个指定的宽度 width 居中的字符串,如果 width 小于字符串宽度直接返回字符串,否则使用 fillchar 去填充。
- ljust(width,fillchar) 与center()方法不同的就是返回一个指定宽度width居左的字符串。
- rjust(width,fillchar) 与center()方法不同的就是返回一个指定宽度width居右的字符串。
str = "hello world" print("str.ljust(20,'*'):",str.ljust(20,'*')) print("str.center(20,'*'):",str.center(20,'*')) print("str.rjust(20,'*'):",str.rjust(20,'*')) #fillchar只能是单字符。
str.ljust(20,'*'): hello world*********
str.center(20,'*'): ****hello world*****
str.rjust(20,'*'): *********hello world - lstrip(chars) 截掉字符串左边的空格或指定字符串中的每个字符,返回截取后的字符串
- rstrip(chars) 截掉字符串右边的空格或者指定字符串的每个字符,返回截取后的字符串
- strip(chars) 同时实现lstrip()和rstrip()方法
str = ' hello world ' print(str.lstrip()) print(str.lstrip(' h')) print(str.lstrip(' hew')) print(str.rstrip()) print(str.rstrip(' d')) print(str.rstrip(' dlw')) print(str.strip(' hd'))
hello world ello world llo world hello world hello worl hello wor ello worl
- count(sub,start,end) sub是搜索的子字符串,start是开始搜索的下标,end是结束的下标,返回子字符串在字符串中出现的次数。
str = "hello world hello world" sub = "hello" print("‘hello’在字符串中出现了%d次"%(str.count(sub))) print("‘hello’在下标0~16中出现了%d次"%(str.count(sub,0,16))) print(str[0],str[16]) #搜索的范围包括下标为start的字符,不包括下标为end的字符
‘hello’在字符串中出现了2次 ‘hello’在下标0~16中出现了1次 h o
- encode(encoding,errors) encode是编码,使用指定的编码格式编码字符串。encoding是指定使用什么编码方式。errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace','xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。
str = '大大焕' str_utf8 = str.encode("UTF-8",'strict') str_gbk = str.encode("GBK",'strict') print("UTF-8编码:",str_utf8) print("GBK编码:",str_gbk)
UTF-8编码: b'\xe5\xa4\xa7\xe5\xa4\xa7\xe7\x84\x95' GBK编码: b'\xb4\xf3\xb4\xf3\xbb\xc0'
返回值:该方法返回的并不是一个普通的字符串,而是一个bytes对象。
- bytes.decode(encoding,errors) 参数encode是一样的,不过此方法是指定一种方法解码,而调用这个方法的是bytes对象,不是普通的字符串对象。
str = '大大焕' str_utf8 = str.encode("UTF-8",'strict') str_gbk = str.encode("GBK",'strict') print("UTF-8编码:",str_utf8) print("GBK编码:",str_gbk) print("UTF-8 解码:",str_utf8.decode('UTF-8','strict')) print("GBK解码:",str_gbk.decode('GBK','strict')) #如果我们试图用不对应的编码去解码,则会出现错误 str_utf8.decode('GBK','strict')
UTF-8编码: b'\xe5\xa4\xa7\xe5\xa4\xa7\xe7\x84\x95' GBK编码: b'\xb4\xf3\xb4\xf3\xbb\xc0' UTF-8 解码: 大大焕 GBK解码: 大大焕 Traceback (most recent call last): File "C:/Users/dell/PycharmProjects/Python_1/day10/firstPy.py", line 9, in <module> str_utf8.decode('GBK','strict') UnicodeDecodeError: 'gbk' codec can't decode byte 0x95 in position 8: incomplete multibyte sequence
- endswith(suffix,start,end) 用于判断在下标为start~end的字符串中是否以字符串suffix结尾。返回true或者false。
str = 'hello wold' print("是否以字符‘ld’结尾:",str.endswith("ld")) print("在下标2-7形成的字符串%s中,是否以‘ld’结尾:"%str[2:7],
str.endswith('ld',2,7))是否以字符‘ld’结尾: True 在下标2-7形成的字符串llo w中,是否以‘ld’结尾: False
- startswith(suffix,start,end) 用于判断在下标为start~end的字符串中是否以字符串suffix结尾。返回true或者false。
str = 'hello world' print("是否以字符‘he’开头:",str.startswith("he")) print("在下标2-7形成的字符串%s中,是否以‘ld’开头:"%str[2:7], str.startswith('ld',2,7))
是否以字符‘he’开头: True 在下标2-7形成的字符串llo w中,是否以‘ld’开头: False
- expandtabs(tabsize) 将字符串中的tab符号(\t)换为空格,空格的个数为tabsize。
-
str = 'hello\tworld' print("原始字符串:"+str) #原始tabs长度默认为8个空格 print("使用空格替换\\t符号:"+str.expandtabs()) print("使用16个空格替换\\t符号:"+str.expandtabs(16))
原始字符串:hello world 使用空格替换\t符号:hello world 使用16个空格替换\t符号:hello world
- find(str,start,end) 检测字符串中是否包含子字符串 str ,如果指定 start(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。
- rfind(str,start,end) 与find()一样,不过是从右边开始检索。
#find() str = 'abcdefabcdab' print("字符串‘ab’在str当中开始的索引为:",str.find('ab')) print("字符串‘ab’在str从下标3开始的字符串%s中开始的索引为:"%(str[3:]),str.find('ab',3)) #将会返回第一个出现的字符串开始的索引 print("字符串‘ab’是否在str的下标1-6形成的字符串%s中:"%(str[1:6]),str.find('ab',1,6)) #rfind() print("str.rfind('ab'):",str.rfind('ab')) print("str.rfind('ab',1,6):",str.rfind('ab',1,6))
字符串‘ab’在str当中开始的索引为: 0 字符串‘ab’在str从下标3开始的字符串defabcdab中开始的索引为: 6 字符串‘ab’是否在str的下标1-6形成的字符串bcdef中: -1 str.rfind('ab'): 10 str.rfind('ab',1,6): -1
- index(str,start,end) 和find()方法一样,但是如果str不在调用的字符串中,会报一个异常。
- rindex(str,start,end) 和index方法一样,但是从后面开始检索。
-
str = 'abcdefabcdab' print("字符串‘ab’是否在str的下标1-6形成的字符串中:",
str.index('ab',1,6))Traceback (most recent call last): File "C:/Users/dell/PycharmProjects/Python_1/day10/firstPy.py", line 2, in <module> print("字符串‘ab’是否在str的下标1-6形成的字符串中:",str.index('ab',1,6)) ValueError: substring not found
- isalnum() 检测字符串是否由字母和数字组成。如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False。
str = '#123abc' print("str.isalnum():",str.isalnum()) #False str1 = '123' print("str1.isalnum():",str1.isalnum()) #True str2 = 'abc' print("str2.isalnum():",str2.isalnum()) #True
- isalpha() 如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False
- isdigit() 如果字符串只包含数字则返回 True 否则返回 False
str = '123abc' print("str.isdigit():",str.isdigit()) #False print("str.isalpha():",str.isalpha()) #False str1 = 'abc' str2 = '123' print("str1.isalpha():",str1.isalpha()) #True print("str2.isdigit():",str2.isdigit()) #True
str.isdigit(): False str.isalpha(): False str1.isalpha(): True str2.isdigit(): True
- isnumeric() 与isidgit()的性质相差不多,不过它只针对unicode字符串。
- isdecimal() 也是判断字符串是否全部由数字构成。
1 ''' 2 isdigit()、isdecimal()、isnumeric()三者的区别。 3 4 isdigit() 5 True:Unicode字符串,byte数字 6 False:罗马数字、中文数字 7 error:无 8 9 isdecimal() 10 True:Unicode数字 11 False:罗马数字、中文数字 12 error:byte数字 13 14 isnumeric() 15 True:Unicode数字、罗马数字、中文汉字 16 False:无 17 error:byte数字 18 '''
1 str1 = '123' #unicode编码数字 2 str2 = b'123' #byte数字 3 str3 = '一二三' #中文数字 4 str4 = 'ⅠⅡⅢ' #罗马数字 5 print("str1.isdigit():",str1.isdigit()) 6 print("str2.isdigit():",str2.isdigit()) 7 print("str3.isdigit():",str3.isdigit()) 8 print("str4.isdigit():",str4.isdigit()) 9 print('\n')
1 str1 = '123' #unicode编码数字 2 str2 = b'123' #byte数字 3 str3 = '一二三' #中文数字 4 str4 = 'ⅠⅡⅢ' #罗马数字 5 print('str1.isdecimal():',str1.isdecimal()) 6 print('str2.isdecimal():',str2.isdecimal()) 7 print('str3.isdecimal():',str3.isdecimal()) 8 print('str4.isdecimal():',str4.isdecimal()) 9 print('\n')
1 print('str1.isnumeric():',str1.isnumeric()) 2 print('str2.isnumeric():',str2.isnumeric()) 3 print('str3.isnumeric():',str3.isnumeric()) 4 print('str4.isnumeric():',str4.isnumeric())
- islower() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False。
str = 'ABCabc' str1 = 'abcabc' print(str.islower()) #False print(str1.islower()) #True
- isupper() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False。
- lower() 将字符串的字母都转换为小写
- upper() 将字符串的字母都转换为大写
str = '你好,世界,hello WORLD' print('变为小写:',str.lower()) print('变为大写:',str.upper()) 变为小写: 你好,世界,hello world 变为大写: 你好,世界,HELLO WORLD
- casefold() 也是将字符串的字母全变为小写,功能比lower()更强大。
str = 'heLLo WOrlD ' print(str.casefold())
hello world
- isspace() 如果字符串中只含有空白,返回True,否则返回False。
- title() 返回标题化的字符串,及所有单词都是首字母大写,其余小写。
- istitle() 判断字符串是否为标题化的
str = 'hello world' print('str:%-15s是否已经标题化:'%(str),str.istitle()) str = str.title() print('str:%-15s是否已经标题化:'%(str),str.istitle()) str:hello world 是否已经标题化: False str:Hello World 是否已经标题化: True
- join(seq) 将序列中的元素以指定的字符连接生成一个新的字符串。返回通过指定字符连接序列中元素后生成的新字符串。
str1 = '-' str2 = '' list1 = 'hello world' list2 = ['I','l','o','v','e','y','o','u'] print(str1.join(list1)) print(str1.join(list2)) print(str2.join(list2)) h-e-l-l-o- -w-o-r-l-d I-l-o-v-e-y-o-u Iloveyou
输入的参数seq必须是字符串,不能是数字,否则会报错。
- len(str) 返回字符串的长度
str = 'hello world' print(len(str)) 11
- translate(table,deletechars) table是翻译表通过maketrans()方法转换而来。deletechars是字符串中要过滤的字符列表。
inchars = 'eol' #被映射的字符串 outchars = '123' #映射的字符串 trans_table = str.maketrans(inchars,outchars) #制作映射翻译表 str = 'hello world' print(str.translate(trans_table)) #两个str意义是不一样的。第一个是表示str模块,第二个是变量名 '''如果要加上参数deletechars,则要将字符串对象都改为bytes对象
(在字符串前面加b)''' #制作映射翻译表,将字符小写变成大写 bytes_trans_table = bytes.maketrans(b'abcdefghigklmnopqrstuvwxyz',
b'ABCDEFGHIGKLMNOPQRSTUVWXYZ') print(b'hello world'.translate(bytes_trans_table,b'ol')) #去掉原bytes对象中的字符‘o’和‘l’之后映射的字符串h1332 w2r3d b'HE WRD'
- maketrans(intab,outtab) 制作映射翻译表,,intab是要被替换的字符串,outtab是替换的字符串。返回一个映射的字典对象。此方法可以用bytes调用,也可以用str调用。
inchars = 'eol' #被映射的字符串 outchars = '123' #映射的字符串 trans_table = str.maketrans(inchars,outchars) #制作映射翻译表 print(trans_table,type(trans_table))
- min(str)、max(str) 返回字符串str中最小/大的字母
str = 'efghik' print("str中最小的字母是%s,最大的字母是%s"%(min(str),max(str))) 输出: str中最小的字母是e,最大的字母是k
- replace(old,new,max) 把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次。
str = 'my name is kobe' str1 = str.replace('kobe','james') print(str1) str = 'abcabcabcabc' str1 = str.replace('abc','123',3) print(str1)
my name is james 123123123abc
- split(str,num) 通过指定分隔符(默认空格)对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串。str表示以什么分隔符进行切片,num表示切几次。返回一个由切割完的字符串形成的列表。
str = 'kobe is my favorite basketball player' print(type(str.split())) print(str.split()) print(str.split('i')) print(str.split('a',3))
<class 'list'> ['kobe', 'is', 'my', 'favorite', 'basketball', 'player'] ['kobe ', 's my favor', 'te basketball player'] ['kobe is my f', 'vorite b', 'sketb', 'll player']
- splitlines(keepends) 在字符串中按照行(\n,\r,\r\n)分割返回一个包含各行的列表。参数keepends是判断符,默认为False,不包含换行符,若为True,则包含换行符
str = "\nabc\nefg\rhigoror\n" print(str) print(str.splitlines()) print(str.splitlines(True))
abc higoror ['', 'abc', 'efg', 'higoror'] ['\n', 'abc\n', 'efg\r', 'higoror\n']
- swapcase() 将字符串中大写变小写,小写变大写。
str = 'hello WORLD' print(str.swapcase()) HELLO world
字符串的格式化format()方法
主要是使用{}与:来代替%的另一种格式化方法。
format可接受不限个参数,如果没有位置索引,则按先后顺序。format()中的参数全部可以视为一个列表或者元组。
>>> 'i am {},{} years old '.format('kobe',38) 'i am kobe,38 years old ' >>> 'i am {},{} years old '.format('kobe',38,56) 'i am kobe,38 years old ' >>> 'i am {},{} years old '.format('kobe') Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: tuple index out of range >>>
{}可以比format()中的参数少,但不能多,多则会报错。
也可以使用索引来控制。
>>> 'i am {0},{1} years old '.format('kobe',38) 'i am kobe,38 years old ' >>> "i like {0},don't like {1},but my friends like {1}".format('basketball','football') "i like basketball,don't like football,but my friends like football" >>>
也可以设置对应参数
print('i am {name},{age} years old'.format(name = 'kobe',age = 39)) #输出 i am kobe,39 years old
也可以通过字典设置
print('i am {name},{age} years old'.format(**{'name':'kobe','age' :39})) #输出 i am kobe,39 years old
也可以通过控制列表索引
print('i am {0},{1} years old'.format(*['kobe',39])) #输出 i am kobe,39 years old
*与**分别控制列表和字典,相当于将列表和字典的每个元素都变为format的参数。
如果不想使用*,也可以使用如下方法
list = ['kobe',39] print('i am {0[0]},{0[1]} years old'.format(list)) #0不可少,表示索引为0的元素 #输出 i am kobe,39 years old
也可以使用:改变格式,也是采用顺序赋值
demo = "i am {:s},age{:d}".format(*['kobe',39]) print(demo) demo = "i am {:s},age{:d}".format('kobe',39) print(demo) demo = "numbers:{:b},{:o},{:d},{:x},{:X},{:%}".format(15,15,15,15,15,15.5432) print(demo) #o为八进制,b为二进制,x为16进制,X为16进制
输出:
i am kobe,age39
i am kobe,age39
numbers:1111,17,15,f,F,1554.320000%