字符串的方法
字符串英雄的技能
- 查找方法 find
- 替换方法 replace
- 统计方法 count
- 文本对齐 ljust rjust center
- 去除空白 lstrip rstrip strip
- 拆分 split
- 连接 join
- 编码 encode
- 解码 decode
- 格式化输出 format
查找 find

字符串.find(查找内容)
如果找到了,得到内容的索引
如果找不到,得到-1
可以应用于名片管理系统的根据姓名搜索

替换 replace

s = '人生苦短,我用php'
res = s.replace('php','python')
print(res)
统计数量 count
s = '112112'
n = s.count('1')
print(n)
文本对齐
s = '****'
print(s)
r = s.rjust(20)
print(r)
r2 = s.center(20)
print(r2)
绘制等边三角形
i = 1
while i <= 9:
s = '*' * i
if i % 2 == 0:
i += 1
continue
r = s.center(30)
print(r)
i += 1
# print('结束了。。。')
去除空白 strip
In [88]: s = 'zhangsan '
In [89]: s
Out[89]: 'zhangsan '
In [90]: s.rstrip()
Out[90]: 'zhangsan'
In [91]: n = ' lish '
In [92]: n.lstrip()
Out[92]: 'lish '
In [93]: n.lstrip().rstrip()
Out[93]: 'lish'
In [94]: n
Out[94]: ' lish '
In [95]: n.strip()
Out[95]: 'lish'
拆分 split

字符串.split(拆分的依据)
连接 join

连接符.join(有序容器)
编码
把utf8的编码转为字节码

字符串.encode()
字符串.encode('utf8')
解码 decode
把字节码转换成utf8的字符串

格式化输出 format

字符串.format(参数1,参数n)
本文详细介绍了字符串的各种常用操作方法,包括查找、替换、统计、对齐、拆分、连接、编码和解码等。通过实例展示了如何使用这些方法进行高效的数据处理,适用于名片管理系统等应用场景。
1142

被折叠的 条评论
为什么被折叠?



