一、转化为文本格式.str()
str为string(字符串)缩写.
[1]
a=123
type(a)
[1] int 整数
[2] 转化为文本
a=str(a)
type(a)
[2] str 字符串
二、大小写转换.lower() 全部小写
.upper() 全部大写
.capitalize() 首字母大写
[3]
a="You are smart."
a.lower()
a.upper()
a.capitalize()
[3]
'you are smart.'
'YOU ARE SMART.'
'You are smart.'
三、抽取[]
Python计数从0开始.
[4]
a="smart"
for i,j in enumerate(a):
print(i,j)
[4]
0 s
1 m
2 a
3 r
4 t
[5] 提取第2-4字符
a[1:4]
[6] 隔1个位提取
a[::2]
[7] 逆序
a[::-1]
[5] 'mar'
[6] 'sat'
[7] 'trams'
四、拆分.split()
[8] 以空格为分割线, 切割句子
a="You are smart."
a.split()
[8] ['You', 'are', 'smart.']
[9] 以空格为分割线, 切割句子, 最多切割1次
a.split(maxsplit=1)
[9] ['You', 'are smart.']
[10] 以句号为分割线, 切割句子
a.split(sep=",")
[10] ['You are smart', '']
此处的sep, 为separator (分隔符号)缩写.
五、拼接+
.join()+
[11]
a="You"
b="are
a+" "+ b
[11] 'You are'.join()
[12]用空格拼接
b=['You', 'are', 'smart.']
" ".join(b)
[12] 'You are smart.'
六、计数.count()
[13] 字母a出现几次
string='You are smart.'
string.count("a")
[14] 从第6位开始统计, a出现的频率
string.count("a", 5)
[15] 从第6位统计到倒数第五位, 统计a的频率
string.count("a",5,-5)
[13] a
[14] 1
[15] 0
统计位置默认为0.
七、查找.find()
[16] 返回a的索引
string='You are smart.'
string.find("a")
[17] 返回z的索引
string.find("z")
[16] 4 (只返回第一个)
[17] -1 (没有找到)
八、替换.replace()
[18] 把You替换为I
string='You are smart.'
string.replace("You","I")
[18] 'I are smart.'
没有找替换目标, 返回原文本.
九、去首尾换行符和空格.strip()
.lstrip()
.rstrip()
\n在python中默认为换行符
[19]
string="You are\nsmart"
print(string)
[19]
You are
smart
[20]去首位空格, 末尾换行符
string=" You are smart\n"
print(string.strip())
[21] 只去首位空格
print(string.lstrip())
[22 只去末尾
print(string.rstrip())
[20]You are smart
[21]
You are smart
lstrip 是left strip缩写.
[22] You are smart
相关阅读:沧海为水:Python文本处理(二)文本格式化(formatting)zhuanlan.zhihu.com
这是我的第2篇Python学习笔记. 题图来自unsplash.