字符串
字符串的基本特点
字符串的本质是:字符序列。Python 的字符串是不可变的,我们无法对原字符串做任何修改。但可以将字符串的一部分复制到新创建的字符串,达到“看起来修改”的效果。 Python 不支持单字符类型,单字符也是作为一个字符串使用的。
replace()实现字符串替换
字符串不可改变。但是,我们确实有时候需要替换某些字符。这时,只能通过创建新的字符串来实现
a = 'abcdefghijklmnopqrstuvwxyz'
a = a.replace('c','高')
print(a)
output: ‘ab高defghijklmnopqrstuvwxyz’
整个过程中,实际上我们是创建了新的字符串对象,并指向了变量 a,而不是修改了以前的 字符串。 内存图如下: 
字符串切片 slice 操作
切片 slice 操作可以让我们快速的提取子字符串。标准格式为: [起始偏移量 start:终止偏移量 end:步长 step] 典型操作(三个量为正数的情况)如下: 
其他操作(三个量为负数)的情况: 
split()分割和 join()合并
split()可以基于指定分隔符将字符串分隔成多个子字符串(存储到列表中)。如果不指定分隔符,则默认使用空白字符(换行符/空格/制表符)。
a = "to be or not to be"
a.split()
join()的作用和 split()作用刚好相反,用于将一系列子字符串连接起来。示例代码如下:
a = ['sxt','sxt100','sxt200']
'*'.join(a)
拼接字符串要点: 使用字符串拼接符+,会生成新的字符串对象,因此不推荐使用+来拼接字符串。推荐使用 join 函数,因为 join 函数在拼接字符串之前会计算所有字符串的长度,然后逐一拷贝,仅新建一次对象。
字符串查找


去除首尾信息
通过 strip()去除字符串首尾指定信息。通过 lstrip()去除字符串左边指定信息, rstrip()去除字符串右边指定信息
"*s*x*t*".strip("*")
"*s*x*t*".lstrip("*")
"*s*x*t*".rstrip
" sxt ".strip()
大小写转换


其他方法
- isalnum() 是否为字母或数字
- isalpha() 检测字符串是否只由字母组成(含汉字)。
- isdigit() 检测字符串是否只由数字组成。
- isspace() 检测是否为空白符
- isupper() 是否为大写字母
- islower() 是否为小写字母
数字格式化
浮点数通过 f,整数通过 d 进行需要的格式化
a = "我是{0},我的存款有{1:.2f}"
a.format("小可爱",3888.234342)
output: ‘我是小可爱,我的存款有 3888.23’
|