前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python -- 操作字符串[3/3]

Python -- 操作字符串[3/3]

作者头像
py3study
发布2020-01-03 11:29:28
6060
发布2020-01-03 11:29:28
举报
文章被收录于专栏:python3

 1,splitlines()


代码语言:javascript
复制
yuan@ThinkPad-SL510:~$ ipython -nobanner  In [1]: multiline_string = """This    ...: is    ...: a multiline    ...: piece of    ...: text"""  In [2]: multiline_string.spli multiline_string.split       multiline_string.splitlines  In [2]: multiline_string.split() Out[2]: ['This', 'is', 'a', 'multiline', 'piece', 'of', 'text']  In [3]: lines = multiline_string.splitlines()  In [4]: lines Out[4]: ['This', 'is', 'a multiline', 'piece of', 'text'] 

糊涂了?仔细看13行和18行的a multilines。

2,join()


代码语言:javascript
复制
yuan@ThinkPad-SL510:~$ ipython -nobanner  In [1]: some_list = ['one','two','three','four']  In [2]: ','.join(some_list) Out[2]: 'one,two,three,four'  In [3]: '\t'.join(some_list) Out[3]: 'one\ttwo\tthree\tfour'  In [4]: ''.join(some_list) Out[4]: 'onetwothreefour' 

很简单不是吗?

没那么简单,请看:

代码语言:javascript
复制
yuan@ThinkPad-SL510:~$ ipython -nobanner  In [1]: some_list = range(10)  In [2]: some_list Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  In [6]: ",".join(some_list) --------------------------------------------------------------------------- TypeError                                 Traceback (most recent call last)  /home/yuan/<ipython console> in <module>()  TypeError: sequence item 0: expected string, int found   In [4]: ",".join([str(i) for i in some_list]) Out[4]: '0,1,2,3,4,5,6,7,8,9'  In [5]: ",".join(str(i) for i in some_list) Out[5]: '0,1,2,3,4,5,6,7,8,9' 

很显然join只能处理字符串序列,str()即可。

3,replace()


代码语言:javascript
复制
yuan@ThinkPad-SL510:~$ ipython -nobanner  In [1]: replacable_string = "trancendental hibernational nation"  In [2]: replacable_string.replace("nation","natty") Out[2]: 'trancendental hibernattyal natty' 

这个没啥好说的,很简单

但是必须说下:replace()和前边说的strip()一样,会创建一个新字符串,而不是对字符串进行行内修改。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档