Python -- 操作字符串[3/3]
短信预约 -IT技能 免费直播动态提醒
1,splitlines()
- 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()
- 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'
很简单不是吗?
没那么简单,请看:
- 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()
- 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()一样,会创建一个新字符串,而不是对字符串进行行内修改。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341