字符串与文本操作
字符串:
- Python 2和Python 3最大的差别就在于字符串
- Python 2中字符串是byte的有序序列
- Python 3中字符串是unicode的有序序列
- 字符串是不可变的
- 字符串支持下标与切片
# 证明字符串支持切片和下标 In [40]: s = ‘hello world!‘ In [41]: s[0] Out[41]: ‘h‘ In [42]: s[0:3] Out[42]: ‘hel‘ In [43]: s[::-1] Out[43]: ‘!dlrow olleh‘ # 证明字符串是不可变类型 In [44]: s[0] = ‘L‘ --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-44-887f788ca844> in <module>() ----> 1 s[0] = ‘L‘ TypeError: ‘str‘ object does not support item assignment
字符串格式化(两种方式)
- Python字符串支持两种方式格式化
- print style format
- format方法
print style format
template % tuple (1) template % dict (2) template 为带有一些标记的字符串,使用 tuple 中的元素一次填充 template 为带有一些标记的字符串,使用 dict 中的values按key填充
template 的一般格式:
% (key) flag conversion (1) (2) (3) (4) % 开始 1.可选的 (key) 如果指定了key, 将从字典中获取对应的value, 否则根据位置从元组中获取 2.可选的 flag 3.必选的 conversion
实例:
In [45]: ‘I love %s‘ % (‘Python‘, ) Out[45]: ‘I love Python‘ In [46]: ‘I love %(name)s‘ % {‘name‘: ‘Python‘} Out[46]: ‘I love Python‘ In [47]: ‘I love %s, %s is my first lang‘ % (‘Python‘, ‘PY‘) Out[47]: ‘I love Python, PY is my first lang‘
flag
Flag | 说明 | 实例 |
---|---|---|
# |
此处 # 代表一个数字,指定宽度,如果宽度不够,会更具以下的规则填充
|
‘%3s‘ % (‘a‘, ) → ‘••a‘
|
0 |
使用0填充,仅适用于数字 |
‘%03d‘ % (1,) → ‘001‘
|
• |
使用空格填充,默认行为 |
’%•3d‘ % (1,) ` → ‘••1‘ |
flag
Flag | 说明 | 实例 |
---|---|---|
- |
右边使用空格填充 |
‘%-3d‘ % (1,) → ‘1••‘
|
+ |
填充之前增加`+` 仅对于正数 |
‘%+03d‘ % (1, ) → ‘+01‘
|
Conversion
符号 | 说明 | 符号 | 说明 |
---|---|---|---|
d |
整数 |
i |
整数 |
o |
八进制整数 |
u |
整数,已废弃 |
x |
小写十六进制整数 |
X |
大写十六进制整数 |
f |
浮点数 |
F |
浮点数 |
e |
小写科学计数法 |
E |
大写科学计数法 |
Conversion
符号 | 说明 | 符号 | 说明 |
---|---|---|---|
g |
同f, 如果指数小于-4,同e |
G |
同f, 如果指数小于-4,同E |
c |
字符,接收unicode编码或单字符字符串 |
a |
字符串,使用 ascii 函数转换
|
r |
字符串,使用 repr 函数转换
|
format函数
template.format(*args, **kwargs) (1) (2) (3) (4)
template
使用{}
标示变量{}
或{\d+}
使用*args
按顺序填充{key}
使用**kwargs
按key填充- Format String Syntax
In [48]: d = {‘a‘:1, ‘b‘: 2, ‘c‘:3} In [49]: for k,v in d.items(): ....: print(‘key/value : {0} ==> {1}‘.format(k,v)) ....: key/value : b ==> 2 key/value : a ==> 1 key/value : c ==> 3
字符串常用操作
- 字符串连接
join
In [50]: lista =[‘I‘, ‘love‘, ‘Python‘] In [51]: ‘ ‘.join(lista) Out[51]: ‘I love Python‘
- 字符串分割
split
,rsplit
,splitlines
,partition
,rpartition
In [53]: s.split(‘:‘,1) Out[53]: [‘root‘, ‘x:0:0:root:/root:/bin/bash‘]
- 字符串修改-大小写
capitalize
,title
,lower
,upper
,swapcase
# 此行第一个首字母大写 In [58]: s.capitalize() Out[58]: ‘I love python‘ # 每个单词的首字母大写 In [59]: s.title() Out[59]: ‘I Love Python‘ # 全部转化为小写 In [60]: s.lower() Out[60]: ‘i love python‘ # 全部转化为大写 In [61]: s.upper() Out[61]: ‘I LOVE PYTHON # 大小写互换 In [63]: s = ‘i Love Python‘ In [64]: s.swapcase() Out[64]: ‘I lOVE pYTHON‘
- 字符串修改-填充清除
center
,ljust
,rjust
,zfill
,strip
,rstrip
,lstrip
# center 填充,一般用在格式化输出 In [65]: s = ‘Python‘ In [67]: s.center(20,‘-‘) Out[67]: ‘-------Python-------‘ # 去掉换行符strip() In [68]: s = ‘abc\n‘ In [69]: s.strip() Out[69]: ‘abc‘
- 字符串判断
startswith
,endswith
,is*
In [81]: s = ‘abcdefg‘ # 字符串是以a开头 In [83]: s.startswith(‘a‘) Out[83]: True In [84]: if s.startswith(‘a‘): ....: print(‘ok‘) ....: ok # 是以g为结尾的. In [85]: if s.endswith(‘g‘): print(‘ok‘) ....: ok
- 字符串查找替换
count
,find
,rfind
,index
,rindex
,replace
s = ‘root:x:0:0:root:/root:/bin/bash\n‘ # count统计个数 In [103] : s.count(‘root‘) Out[103] : 3
In [87]: s = ‘root:x:0:0:root:/root:/bin/bash\n‘ # replace进行替换,可以指定替换次数. In [88]: s.replace(‘root‘, ‘admin‘, 1) Out[88]: ‘admin:x:0:0:root:/root:/bin/bash\n‘
str与bytes
- Python3中严格区分了文本和二进制数据
- Python2并没有严格区分
- 文本数据使用str类型,底层实现是unicode
- 二进制数据使用bytes类型,底层是byte
- str使用encode方法转化为bytes
- bytes方法使用decode方法转化为str
- 由于清晰的区分文本和二进制,Python3解决了大多数Python2的编码问题
时间: 2024-08-06 07:55:38