python3 文本处理_Python文本处理(一)基础小抄

一、转化为文本格式.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.comv2-448ccda7e4e25ed738f8ea6f0a253cfb_180x120.jpg

这是我的第2篇Python学习笔记. 题图来自unsplash.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值