Python3基础数据类型-字符串


一、昨日内容回顾
1.格式化输出

% 表示占位符
%s 表示字符串
%d 表示数字

2.编码:
ascii 只能显示英文,特殊字符,数字
万国码:unicode最开始16位,中文不够32位,4字节
占用资源多
升级:utf-8 utf-16 utf-32
utf-8:最少用一个字节,8位表示一个英文
欧洲16位,两个字节
亚洲24位,三个字节

gbk:中文,两个字节表示中文,只能用于中文和英文

二、数据类型
1.int
1,2,3用于计算

2.bool 布尔型
True\False 用于判断

3.str 字符串 用引号引起来的 存储少量数据

4.list列表 存储大量的数据 可变数据类型
[1,2,3,'abc',[3,2,1]]

5.元组tuple 只读
(1,2,3,'av')

6.字典dic{} 可变数据类型 存储大量数据
{'name':'felix','age':30,'id':10024087}

7.集合:
{1,2,3,44,'abcd'}

三、int
1.bit_legth() 返回数字转化为2进制的位数

a = 37
print(a.bit_lenth())

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6

2.int.from_bytes(cls, *args, **kwargs)
待了解
3.int.to_bytes(self, *args, **kwargs)
(self, *args, **kwargs)

四、bool 布尔值 True False
1.int -> str
s = str(10)

2. str -> int
i = int(str('123'))

3.int -> bool 非零为True,0位False
i = 5
bool(i)
True

4.bool -> int
True
int(True)
1

while 1: #效率比True高
pass
while True:
pass

5.str -> bool 字符为空,返回False,字符为非空,返回为True
s = 'felix'
bool(s)
True

s = ''
bool(s)
False

总结:0、None、空字符串,空列表、空元祖、空字典 都为Flase
真值表
对象 值

"" 假
"string" 真
0 假
>=1 真
<=-1 真
()空元祖 假
[]空列表 假
{}空字典 假
None 假



五、字符串
1.字符串的定义 初始化
一个个字符组成的有序的序列,是字符的集合
使用单引号,双引号,三引号引住的字符序列

字符串是不可变的对象

Python3起,字符串就是Unicode类型
举例:
s1 = 'string'
s2 = "string2"
s3 = '''this's a 'string' '''
s4 = 'hello \n mageedu.com'
s5 = r "hello \n mageedu.com"
s6 = 'c:\windows\nt'
s7 = R "c:\windows\nt"
s8 = 'c:\windows\\nt'
sql = """select * from user where name='tom' """

2.字符串元素访问--下标
字符串支持使用索引访问
sql = """select * from user where name='tom' """
sql[4] = 'c' #字符串'c'

有序的字符集合,字符序列
for c in sql:
print(c)
print(type(c)) #什么类型? str

可迭代
lst = list(sql)

六、字符串索引和切片
1.索引index 索引号从左到右依次为 0,1,2...n
索引号从右到左依次为 -1,-2,-3 ...n
s = 'abcdefg'
s1 = s[0]
'a'
2.索引切片 str[start[:end]] 顾头不顾尾 左闭右开
(1)取单个元素
s = 'abcdefg'
s1 = s[2]
'c'
(2)取中间部分元素
s = 'abcdefg'
s1 = s[1:3]
'bc'

(2)取索引号后面所有的元素
s = 'abcdefg'
s1 = s[1:]
'bcdefg'

(3)取所有元素
s = 'abcdefg'
s1 = s[:]
'abcdefg'

(3)s[start:end:step] 取步长为step的元素
s = 'abcdefg'
s1 = s[0:5:2]
'ace'

(4)反着取不包含索引为0的元素
s = 'abcdefg'
s1 = s[4:0:-1]
'edcb'

(5)反着取包含索引为0的元素
s = 'abcdefg'
s1 = s[4::-1]
'edcba'

s = 'abcdefg'
s1 = s[-1::-1]
'gfedcba'

s = 'abcdefg'
s1 = s[::-1]
'gfedcba'

(6)反着取包含索引为0的元素,且取指定步长的元素
s = 'abcdefg'
s1 = s[4::-2]
'eca'

七、字符串+连接

+ -> str
将2个字符串连接在一起
返回一个新的字符串

八、字符串join连接

"string".join(iterable) -> str
将可迭代对象连接起来,使用string作为分隔符
可迭代对象本身元素都是字符串
返回一个新字符串

exp:
lst = ['1','2','3']
print("\"".join(lst)) #分隔符是双引号
'1"2"3'
print(" ".join(lst))
'1 2 3'
print("\n".join(lst))
'1\n2\n3'

lst = ['1',['a','b'],'3']
print(" ".join(lst)) TypeError: sequence item 1: expected str instance, list found


九、字符串分隔

分隔字符串的方法分为2类
1.split系 #切割 返回列表
将字符串按照分隔符分割成若干字符串,并返回列表 list[]

(1)split(sep= None,maxsplit=-1) -> list of strings
从左到右
sep指定分隔符。缺省的情况下空白字符串作为分隔符
maxsplit指定分隔的次数,-1表示遍历整个字符串

s1 = "I'm \ta super student."
s1.split() -> ["I'm", 'a', 'super', 'student.']
s1.split('s') -> ["I'm \ta ", 'uper ', 'tudent.']
s1.split('super') -> ["I'm \ta ", ' student.']
s1.split('super ') -> ["I'm \ta ", 'student.']
s1.split(' ') -> ["I'm", '\ta', 'super', 'student.']
s1.split(' ',maxsplit=2) -> ["I'm", '\ta', 'super student.']
s1.split(' \t',maxsplit=2) -> ["I'm", 'a super student.']
s1.split(' \t',2) -> ["I'm", 'a super student.']


(2)reslit(sep=None,maxsplit=-1) -> list of strings
从右向左
sep指定分隔字符串,缺省的情况下空白字符串作为分隔符
maxsplit指定分隔的次数,-1表示遍历整个字符串


s1 = "I'm \ta super student."
s1.rsplit() ->
s1.rsplit('s') ->
s1.rsplit('super') ->
s1.rsplit('super ') ->
s1.rsplit(' ') ->
s1.rsplit(' ',maxsplit=2) ->
s1.rsplit(' \t',maxsplit=2) ->
s1.rsplit(' \t',2) ->

(3)splitlines([keepends]) -> list of strings
按照行来分切字符串
keepends指的是是否保留分隔符
行分隔符包括\n、\r\n、\r等

exp:
'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
'ab c\n\nde fg\rkl\r\n'.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

s1 = '''I'm a super student.
You're a super teacher.'''
print(s1)
"I'm a super student.\nYou're a super teacher."
print(s1.splitlines())
["I'm a super student.", "You're a super teacher."]

print(s1.splitlines(True))
["I'm a super student.\n", "You're a super teacher."]


2.partition系*** 返回元组

(1)partition(sep) -> (head,sep,tail)

从左到右,遇到分隔符就把字符串分隔成两部分,返回 头、分隔符、尾三部分的三元组;
如果没有找到分隔符,就返回 头,2个空元素的三元组
sep分隔字符串,必须指定

exp
s1 = "I'm a super student"

s1.partition('s')
("I'm a ", 's', 'uper student')
s1.partition('stu')
("I'm a super ", 'stu', 'dent')
s1.partition('')
报错 ValueError: empty separator
s1.partition('abc')
("I'm a super student", '', '')

(2)rpartition(sep) -> (head,sep,tail)

从右到左,遇到分隔符就把字符串分隔成两部分,返回 头、分隔符、尾三部分的三元组;
如果没有找到分隔符,就返回 头,2个空元素的三元组


十、字符串大小写

1.upper()
将字符全部改为大写

2.lower()
将字符全部改为小写

3.swapcase()
将字符大小写交换

十一、字符串排版
1.title() -> str 将字符串标题的每个单词都大写

s1 = "I'm a super student."
s1.titile()
"I'M A Super Student."

2.capitalize() -> str 将字符串首个单词大写

"I'm a super student."

3.center(width,[,fillchar]) -> str 将字符串居中
width 打印宽带
fillchar 填充的字符

s1.center(30)
" I'm a super student. "
s1.center(30,'*')
"*****I'm a super student.*****"

4.zfill(width) -> str width打印宽带,居右,左边用0填充

s1.zfill(30)
"0000000000I'm a super student."

5.ljust(width,[,fillchar]) -> str 左对齐
s1.ljust()
"I'm a super student. "

6.rjust(width,[,fillchar]) -> str 右对齐
s1.rjust()
" I'm a super student."

十二、字符串修改***

1.replace(old,new[,count]) -> str
字符串中找到匹配替换为新子串,返回新字符串
count表示替换几次,不指定就是全部替换

exp:
'www.baidu.com'.replace('w','g')
'www.baidu.com'.replace('w','g',2)
'www.baidu.com'.replace('w','g',3)
'www.baidu.com'.replace('ww','g',2)
'www.baidu.com'.replace('w','python',2)



2.strip([chars]) -> str
从字符串两端去除指定的字符集chars中的所有字符
如果chars没有指定,去除两端的空白字符

exp:
s = "\r \n \t Hello Python \n \t"
s.strip()
'Hello Python'
s = "I am very very very sorry "
s.strip('Iy')
' am very very very sorr '
s.strip('Iy ')
'am very very very sorr'
3.lstrip([chars]) -> str 从左开始


4.rstrip([chars]) -> str 从右开始



十三、字符串查找*

1.find(sub,[start[,end]]) -> int (从0开始的正整数,如果返回-1则表示没有找到)
在指定的区间[start,end),从左到右,查找子串sub,找到返回索引,没找到返回-1

2.rfind(sub,[start[,end]]) -> int(从0开始的正整数,如果返回-1则表示没有找到)
在指定的区间[start,end),从右到左,查找子串sub,找到返回索引,没找到返回-1

exp:
s = "I am very very very sorry."
s.find('very')
5
s.find('very',5)
5
s.find('very',6,13)
-1 #未找到
s.rfind('y',10)
24
s.rfind('y',10,15)
13
s.rfind('very',-10,-1)
-1


3.index(sub,start[,end]) -> int (从0开始的正整数,如果没有则抛出异常)
在指定的区间[start,end],从左到右,查找子串sub,找到返回索引,没找到抛出异常ValueError

4.rindex(sub,start[,end]) -> int (从0开始的正整数,如果没有则抛出异常)
在指定的区间[start,end],从右到左,查找子串sub,找到返回索引,没找到抛出异常ValueError


时间复杂度O(n)
index\find\count都是O(n)
随着字符串规模的增大,而效率下降

5.len(string)
返回字符串的长度,即字符的个数

6.count(sub[,start[,end]]) -> int
在指定区间[start,end],从左到右,统计子串sub出现的个数

exp:
s = "I am very very very sorry."
s.count('very')
3
s.count('very',5)
3
s.count('very',10,14)

十四、字符串判断***

1.endswith(suffix,[,start[,end]]) -> bool
在指定的区间[start,end],字符串是否有suffix结尾

2.startswith(suffix,[,start[,end]]) -> bool
在指定的区间[start,end],字符串是否有suffix开头

exp:
s = "I am very very very sorry."
s.startswith('very')
True
s.startswith('very',5)
True
s.startswith('very',5,9)
True
s.endswith('very',5,9)
True
s.endswith('very',5,-1)
False
s.endswith('very',5,100)
False

3.isalnum() -> bool 是否是字母和数字的组成

4.isalpha()是否是字母

5.isdecimal()是否只包含十进制数字

6.isdigit()是否全部数字(0-9)

7.isidentifier()是不是字母和下划线开头,其他都是字母,数字,下划线

8.islower()是否都是小写

9.isupper()是否都是大写

10.isspace()是否只包含空白字符

11.in 或者 not in
a = 'felix.wang'
b = 'wang'
if b in a:
print(b)
执行结果:
wang

24.有限循环
s = 'abcdefgh'
for i in s:
print(i)


十五、字符串格式化
字符串的格式化是一种拼接字符串输出样式的手段,更灵活方便
join拼接只能使用分隔符,且要求被拼接的是可迭代对象
+ 拼接字符串还算方便,但是非字符串需要先转化为字符串才能拼接

1.在2.5版本之前,只能使用print style 风格的printf函数

print-style formatting,来自C语言的printf函数
格式要求
占位符:使用%和格式字符组成,如 %s,%d等
s调用str,r会调用repr(),所有对象都可以被这两个转换
占位符中还可以插入修饰字符,例如%03d表示打印3个位置,不够前面补零
format %values 格式化字符串和被格式的值直接使用%分隔
values只能是一个对象,或是一个和格式字符串占位符数目相等的元组,或一个字典


prinf-style formatting

"I am %03d" %(20,)
'I am 020'

'I like %s.'%'Python'
'I like Python.'

''%3.2f%%,0x%x,0x%02x'%(89.7654,10,15)
'89.77%,0xa,0x0f'

'%06.2f%%,0x%x,0x%02x'%(89.7654,10,15)
'089.77%,0xa,0x0f'

"I am %5d" %(20,)
'I am 20'

"I am %-5d" %(20,)
'I am 20 '


2.Python3.0版本之后推荐使用format函数格式字符串语法----Python鼓励使用
"{}{xxx}".format(*args,**kwargs) -> str
arg是位置参数,是一个元组
kwargs是关键字参数,是一个字典
花括号表示占位符
{}表示按照顺序匹配位置参数,{n}表示取位置参数索引为n的值
{xxx}表示在关键字参数中搜索名称一致的
{{}} 表示打印花括号

(1)位置参数
"{}:{}".format('192.168.1.100','8888'),这就是按照位置顺序用位置参数替换前面的格式字符串的占位符
'192.168.1.100:8888'
(2)关键字参数或命名参数
"{server}{1}:{0}".format(8888,'192.168.1.100',server='Web Server Info:')
'Web Server Info:192.168.1.100:8888'
位置参数按照序号匹配,关键字参数按照名称匹配

(3)访问元素
"{0[0]}.{0[1]}".format(('mageedu','com'))
'mageedu.com'
(4)对象属性访问
from collections import namedtuple
Point = namedtuple('Point','x y')
p = Point(4,5)
"{{{0.x},{0.y}}}".format(p)
'{4,5}'

(5)对齐
'{0}*{1}={2:<2}'.format(3,2,2*3)
'3*2=6 '
'{0}*{1}={2:<02}'.format(3,2,2*3)
'3*2=60'
'{0}*{1}={2:>02}'.format(3,2,2*3)
'3*2=06'

'{:^30}'.format('centerd')
' centerd '

'{:#^30}'.format('centerd')
'###########centerd############'

(6)进制
"int:{0:d};hex:{0:x};oct:{0:o};bin:{0:b}".format(42)
'int:42;hex:2a;oct:52;bin:101010'

"int:{0:d};hex:{0:#x};oct:{0:#o};bin:{0:#b}".format(42)
'int:42;hex:0x2a;oct:0o52;bin:0b101010'

octes = [192,168,0,1]
'{:02x}{:02x}{:02x}{:02x}'.format(*octes) * 把每个元素分解
'c0a80001'

其他
a2 = "hqw\t"
#\t前面的补全
# 默认将一个tab键变成8个空格,如果tab前面的字符长度不足8个,则补全8个,如果tab键前面的字符长度超过8个不足16个则补全16个,以此类推每次补全8个。
ret4 = a2.expandtabs()
print(ret4)


猜你喜欢

转载自www.cnblogs.com/Felix-DoubleKing/p/9664262.html