内置数据结构-字符串

字符串是一种序列,支持切片操作,但是不可变,在python3中是unicode序列,在2中是byte序列

字符串连接

+号可以连接多个字符串,但是不推荐,因为每次连接都会生成新的对象

join连接的列表中的元素必须全部是字符串
In [136]: lst3
Out[136]: ['a', 3, 2, 1, 'hello list', 'a', 10, 'head']

In [137]: ''.join(lst3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-137-81ba8f3237dc> in <module>()
----> 1 ''.join(lst3)

TypeError: sequence item 1: expected str instance, int found

In [138]: l = ['life', 'is', 'short', 'I', 'use', 'python']



In [139]: ''.join(l)
Out[139]: 'lifeisshortIusepython'

In [140]: ' '.join(l)
Out[140]: 'life is short I use python'

字符串分割

split()方法,默认以空白字符分割, 可以指定分隔符和分隔的次数,从左向右分隔

In [142]: s
Out[142]: 'life is short I use python'

In [143]: s.split()
Out[143]: ['life', 'is', 'short', 'I', 'use', 'python']

In [144]: s2 = 'a\tb\tc'

In [146]: s2
Out[146]: 'a\tb\tc'

In [147]: s2.split()
Out[147]: ['a', 'b', 'c']

In [148]: s2.split('\t')
Out[148]: ['a', 'b', 'c']

In [149]: s2.split('\t', 1)
Out[149]: ['a', 'b\tc']

rsplit(),与split类似,但是顺便是从右向左分隔
splitlines()按行分隔,参数True表示分隔后保留换行符

In [150]: s3 = 'hello,world\nhello python\nhello you can do it'

In [151]: s3.splitlines()
Out[151]: ['hello,world', 'hello python', 'hello you can do it']

In [152]: s3.splitlines(True)
Out[152]: ['hello,world\n', 'hello python\n', 'hello you can do it']

partition(), rpartition()返回一个三个元素的元组

In [153]: s3.partition('\n')
Out[153]: ('hello,world', '\n', 'hello python\nhello you can do it')


In [154]: s3.rpartition('\n')
Out[154]: ('hello,world\nhello python', '\n', 'hello you can do it')

字符串的修改

capitalize() 将第一个单词首字母小写转成大写,其他的大写换成小写

In [155]: s
Out[155]: 'life is short I use python'

In [156]: s.capitalize()
Out[156]: 'Life is short i use python'

title()将每个单词的首字母变成大写

In [163]: s
Out[163]: 'life is short I use python'

In [164]: s.title()
Out[164]: 'Life Is Short I Use Python'

lower() ,upper()将所有的字母转成小写/大写

In [165]: s
Out[165]: 'life is short I use python'

In [166]: s.lower()
Out[166]: 'life is short i use python'

In [167]: s.upper()
Out[167]: 'LIFE IS SHORT I USE PYTHON'

swapcase()大小写互相转换

In [168]: s.swapcase()
Out[168]: 'LIFE IS SHORT i USE PYTHON'

center()字符串居中

In [169]: s.center(50)
Out[169]: '            life is short I use python            '

In [170]: s.center(50, '#')
Out[170]: '############life is short I use python############'

rjust(), ljust()让字符串在右边、左边显示

In [171]: s.ljust(50)
Out[171]: 'life is short I use python                        '

In [172]: s.ljust(50, '$')
Out[172]: 'life is short I use python$$$$$$$$$$$$$$$$$$$$$$$$'

zfill() 如果给定的长度大于字符串的长度,用0填充

In [175]: s.zfill(50)
Out[175]: '000000000000000000000000life is short I use python'

readline()逐行读取
readlines()一次全部读取

startswith() 以什么字符开头,可以带下标
endswith() 以什么字符结尾

In [1]: s = '## Life is short, I use Python!!!'

In [2]: s.startswith('#')
Out[2]: True

In [3]: s.startswith('#',3)
Out[3]: False

In [4]: s.startswith('#',2,5)
Out[4]: False

In [5]: s.startswith('#',1,5)
Out[5]: True

In [6]: s.endswith('!')
Out[6]: True

In [7]: s.endswith('!',2,9)
Out[7]: False

字符串查找替换

  • count 统计单个或者多个字符的个数
  • find 从左向右查找字符串的位置,可以有下标参数,没找到返回-1
  • rfind 从右向左查找,可以有下标参数,没找到返回-1
  • indexfind类似,但是找不到会抛出异常
  • rindex 从右向左查找
  • replace 从左向右替换,可以接替换的次数
In [8]: s
Out[8]: '## Life is short, I use Python!!!'

In [9]: s.count('i')
Out[9]: 2

In [10]: s.count('##')
Out[10]: 1

In [11]: s.find('I')
Out[11]: 18

In [12]: s.find('Life')
Out[12]: 3

In [13]: s.rfind('Life')
Out[13]: 3

In [14]: s.rfind('i')
Out[14]: 8

In [15]: s.find('i')
Out[15]: 4

In [16]: s.find('i',10)
Out[16]: -1

In [17]: s.find('ii',10)
Out[17]: -1

In [18]: s.index('i',10)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-18-bba1a8a7f910> in <module>()
----> 1 s.index('i',10)

ValueError: substring not found

In [25]: s
Out[25]: '## Life is short, I use Python!!!'

In [26]: s.replace('use', 'love')
Out[26]: '## Life is short, I love Python!!!'

字符串的格式化

  • printf 风格 类似C语言中的printf ,在2中使用的较多,3中很少使用
    前面是一个字符串模板,后面接一个元组或者字典
In [27]: 'I love %s' % ('Python',)
Out[27]: 'I love Python'

In [28]: '%s is open source and %s is simple' %('python', 'python')
Out[28]: 'python is open source and python is simple'

当一个模板中有多处使用同一个占位符的时候使用字典就比较简洁
In [29]: '%(name)s is open source and %(name)s is simple' %{'name': 'python'}
Out[29]: 'python is open source and python is simple'
  • format 方法 也是模板 调用format()方法
In [30]: '{0} is open source and {0} is simple'.format('python')
Out[30]: 'python is open source and python is simple'

In [31]: '{} is open source and {} is simple'.format('python')
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-31-d48de5a44c97> in <module>()
----> 1 '{} is open source and {} is simple'.format('python')

IndexError: tuple index out of range

In [32]: '{} is open source and {} is simple'.format('python', 'python')
Out[32]: 'python is open source and python is simple'

In [33]: '{0} is open source and {1} is simple'.format('python', 'python')
Out[33]: 'python is open source and python is simple'

In [34]: '{name} is open source and {name} is simple'.format(name='python')
Out[34]: 'python is open source and python is simple'

In [35]: 'my name is {name}, I am {age}'.format(name='loveroot', age=18)
Out[35]: 'my name is loveroot, I am 18'

关键字参数要放在后面 否则会有参数位置错误
In [37]: '{1} {0} {name}'.format('world', 'Hello', name='!')
Out[37]: 'Hello world !'

In [38]: '{1} {0} {name} {2}'.format('world', 'Hello', name='!', '!!!')
  File "<ipython-input-38-f15963a1a293>", line 1
    '{1} {0} {name} {2}'.format('world', 'Hello', name='!', '!!!')
                                                           ^
SyntaxError: positional argument follows keyword argument

传入对象与下标操作

In [39]: class A:
    ...:     def __init__(self):
    ...:         self.x = 1
    ...:         self.y = 2
    ...:         

In [40]: a = A()

In [41]: '{0.x}, {0.y}'.format(a)
Out[41]: '1, 2'

In [42]: l = ['hello', 'world']

In [43]: '{0[0]}, {0[1]}'.format(l)
Out[43]: 'hello, world'

填充与对齐

  • 填充常跟对齐一起使用^<>+-分别是居中左对齐右对齐,正数, 负数,后面带宽度:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
    比如
右对齐 宽度为8
In [15]: '{:>8}'.format('189')
Out[15]: '   189'

用0填充空白
In [16]: '{:0>8}'.format('189')
Out[16]: '00000189'

In [17]: '{:a>8}'.format('189')
Out[17]: 'aaaaa189'

In [57]: '{0:-}'.format(1100)
Out[57]: '1100'

In [58]: '{0:-}'.format(-1100)
Out[58]: '-1100'

In [59]: '{0:+}'.format(-1100)
Out[59]: '-1100'

精度与类型f

其中.2表示长度为2的精度,f表示float类型。
In [44]: '{:.2f}'.format(321.33345)
Out[44]: '321.33'

其他类型
In [54]: '{:b}'.format(17)
Out[54]: '10001'
In [55]: '{:d}'.format(17)
Out[55]: '17'
In [56]: '{:o}'.format(17)
Out[56]: '21'
In [57]: '{:x}'.format(17)
Out[57]: '11'

用,号还能用来做金额的千位分隔符。

In [47]: '{:,}'.format(1234567890)
Out[47]: '1,234,567,890'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容