Python-5-字符串方法,,center>>>


center>>> "The Middle by Jimmy Eat World".center(39)‘ The Middle by Jimmy Eat World ‘>>> "The Middle by Jimmy Eat World".center(39, "*")‘*****The Middle by Jimmy Eat World*****‘find在字符串中查找子串,找到返回子串第一个字符索引,否则返回->>> ‘With a moo-moo here, and a moo-moo there‘.find(‘moo‘)7>>> title = "Monty Python‘s Flying Circus">>> title = "Monty Python‘s Flying Circus">>> title.find(‘Monty‘)0>>> title.find(‘Zirquss‘)-1成员资格检查in智能用于单个字符,而这个可以多个可以指定起点和终点>>> subject = ‘$$$ Get rich now!!! $$$‘>>> subject.find(‘$$$‘)0>>> subject.find(‘$$$‘, 1) # 只指定了起点20>>> subject.find(‘!!!‘)16>>> subject.find(‘!!!‘, 0, 16) # 同时指定了起点和终点-1起点和终点值指定的范围包含起点不包含终点,这是python的惯用做法join与split相反>>> seq = [1, 2, 3, 4, 5]>>> sep = ‘+‘>>> sep.join(seq) # 尝试合并一个数字列表Traceback (most recent call last):File "<stdin>", line 1, in ?TypeError: sequence item 0: expected string, int found>>> seq = [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]>>> sep.join(seq) # 合并一个字符串列表‘1+2+3+4+5‘>>> dirs = ‘‘, ‘usr‘, ‘bin‘, ‘env‘>>> ‘/‘.join(dirs)‘/usr/bin/env‘>>> print(‘C:‘ + ‘\\‘.join(dirs))C:\usr\bin\envlower返回小写版本>>> ‘Trondheim Hammer Dance‘.lower()‘trondheim hammer dance‘title所有单词首字母大写>>> "that‘s all folks".title()"That‘S All, Folks"replace将指定子串都替换为另一个字符串,并返回替换后的结果>>> ‘This is a test‘.replace(‘is‘, ‘eez‘)‘Theez eez a test‘split与join相反,将字符串拆分为序列>>> ‘1+2+3+4+5‘.split(‘+‘)[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]>>> ‘/usr/bin/env‘.split(‘/‘)[‘‘, ‘usr‘, ‘bin‘, ‘env‘]>>> ‘Using the default‘.split()[‘Using‘, ‘the‘, ‘default‘]strip将字符串的开头和末尾的空白删除,并返回删除后的结果>>> ‘ internal whitespace is kept ‘.strip()‘internal whitespace is kept‘translate使用前要先创建一个转换表>>> table = str.maketrans(‘cs‘, ‘kz‘)两个参数为两个长度相同的字符串,指定将第一个字符串中的每个字符都替换为第二个字符串中相应的字符内部存储为unicode>>> table{115: 122, 99: 107}>>> ‘this is an incredible test‘.translate(table)‘thiz iz an inkredible tezt‘第三个参数为指定要将那些字母删除>>> table = str.maketrans(‘cs‘, ‘kz‘, ‘ ‘)>>> ‘this is an incredible test‘.translate(table)‘thizizaninkredibletezt‘判断字符串是否满足特定条件是true,否则falseisalnum、 isalpha、 isdecimal、 isdigit、 isidentifier、 islower、 isnumeric、isprintable、 isspace、 istitle、 isupper

Python-5-字符串方法

评论关闭