码迷,mamicode.com
首页 > 编程语言 > 详细

python2:字符串方法

时间:2017-10-12 21:45:49      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:open   self   映射   gets   浮点   填充   xxx   ndt   不能   

>>>dir(str)
[__add__, __class__, __contains__, __delattr__, __doc__, __eq__, __format__, __ge__, __getattribute__, __getitem__, __getnewargs__, 
__getslice__, __gt__, __hash__, __init__, __le__, __len__, __lt__, __mod__, __mul__, __ne__, __new__, __reduce__, __reduce_ex__,
__repr__, __rmod__, __rmul__, __setattr__, __sizeof__, __str__, __subclasshook__, _formatter_field_name_split, _formatter_parser,
capitalize, center, count, decode, encode, endswith, expandtabs, find, format, index,
isalnum, isalpha, isdigit, islower, isspace, istitle, isupper,
join, ljust, lower, lstrip, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip,
split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill]

 带下划线的略过,只整理可直接被调用的方法。

note:字符串属于不可变对象,所以要得到操作后的结果需进行赋值保存或直接输出

1、大小写转换

>>>s= "hello,world!"

>>>s_capitalize = s.capitalize()#该字符串首字母大写
>>>s_capitalize
Hello,world!

>>>s_title = s.titile()#该字符串中所有单词首字母大写
>>>s_title
Hello,World!

>>>s_upper = s.upper()#该字符串所有字母都大写
>>>s_upper
HELLO,WORLD!

>>>s_lower = s_upper.lower()#该字符串所有字母小写
>>>s_lower
hello,world!

>>>s_swapcase = s_title.swapcase()#该字符串中,大写小写相互转换
>>>s_swapcase
hELLO,wORLD!

 

2、Bool判断

>>>a = "Hello,World!"#该字符串中只要单词首字母大写,其余字母小写为True,否则为False
>>>a.istitle()
True

>>>s = "HELLO,WORLD!"#该字符串字母全大写为True,否则为False
>>>s.isupper()
True

>>>s = "hello,world!"#该字符串字母全小写为True,否则为False
>>>s.islower()
True

>>>s = "abcdefg"#字符串只包含字母为True,否则False
>>>s.isalpha()
True

>>>s = "call110help"
>>>s.isalnum()#字符串只包含数字和字母为True,否则False
True

>>>s = "123456"
>>>s.isdigit()#字符串只包含数字为True,否则为False
True

>>>s =   \t   \n\n
>>>s.isspace()#若字符串只包含空白符为True,否则为False
True


s = "hello,world!‘

>>>s.startswith(hello)#s.startswith(sub),以sub开始为True,否则为False
True

>>>s.endswith(!)#s.endswith(sub),以sub结束为真,否则为False
True

 

3、对齐方式(左、中、右,填充

 

>>>s = "hello"
#指定宽度小于等于len(s)时,返回s
>>>s.rjust(10)#指定对齐后字符串的长度,填充默认空格
         hello

>>>s.rljust(10,*)#s.rjust(width,fillchar=‘ ‘)右对齐
*****hello

>>>s.ljust(10)#左对齐,默认填充空格
hello

>>>s.ljust(10,*)#s.ljust(width,fillchar=‘ ‘)
hello*****

>>>s.center(10)#居中,默认填充空格
  hello

>>>s.center(10,*)#s.center(width,fillchar=‘ ‘)
**hello***

>>>s.center(11,*)#填充字符不够,左边少一个;
***hello***


>>>s.zfill(10)#s.zfill(width),宽度不够就在原字符串左边添加数字零
00000hello

4、查找

>>>s = "hello,world!what is a beautiful flower."
#str.find(sub[,start,end]),默认从索引0处开始全部查找,返回sub首字母的索引值
>>>s.find(o)
4

>>s.rfind(o)#rfiind:从索引-1向0查找,end-->start
34

>>>s.find(wow)#没找到,返回-1
-1

#str.index(sub[,start,end]),默认从索引0处开始全部查找,返回sub首字母的索引值
>>>s.index(o)
4

>>>s.rindex(o)#rindex:从索引-1向0查找,end-->start
34

>>>s.index(wow)#没找到,报ValueError错误
ValueError

5、两端删除

s1 = "     hello     "
s2 = "hello,it‘s me,hello"

#str.strip(chars = ‘ ‘)从两端开始删除,默认删空格
>>>s1.strip()
hello
>>>s2.strip("hello")
,its me,

>>>s1.lstrip()#左删
hello     
>>>s2.lstrip(hello)
,its me,hello

>>>s1.rstrip()#右删
     hello
>>>s2.rstrip(hello)
hello,its me,

6、编码

#编码与解码,python2默认是ASCII码,不兼容中文,需要用到unicode码(中间码)
>>>s = u为中华崛起而读书
>>>s_encode = s.encode(utf8)#从unicode码转化为utf8
>>>s_encode
为中华崛起而读书
#对于部分平台可能需要转码为“gb2312",同理
>>>s_encode.decode(utf8)#从utf8转换为unicode码
为中华崛起而读书

7、分割

>>>s = "hello"
#s.partition(sep[,count]),默认全部进行分块
>>>s.partition(l)
(he,l,lo)

>>>s.rpartition(l)#从右向左
(hel,l,o)

>>>s.partition(well")
(hello,‘‘,‘‘)

#s.split(sep[,count]),默认全部进行切割
>>>s.split(l)
[he,‘‘,o]

>>>s.rsplit(e)#从右向左
[h,llo]

>>>s.split(wow)
[hello]

>>>s = "hello,world!\nI love peace!"
#s.splitlines(keepend = False)
#参数默认是False,按行分割,不保留行尾换行符,返回一个列表,每一行作为一个元素,顺序
>>>s.splitlines()
[hello,world!,I love peace!]

>>>s.splitlines(True)#保留行尾换行符
[hello,world!\n,I love peace!]

 

8、改变\t制表符

s = "hello\tworld\t!"

#\t默认是8个空格
>>>s.expandtabs(10)#将\t设置为10个空格
hello         world!          !

>>>s.expandtabs(2)#将\t设置为两个空格
hello  world  !

 8、计数

>>>s = hello,world!
#索引:默认从左往右,0开始;从右往左,-1开始
>>>s.count(l)#只有一个参数时,表明从左到右,全局查找子串
3

>>>s.count(l,3)#只有一个索引时,表示给定起始位置
2

>>>ss.count(l,1,3)#两个索引表示指定计数的范围
1

9、替换

s = "hello,world!‘
#子串整体替换:s.replace(old,new[count])

>>>s.replace(l,L)#没有给出替换的个数,默认全部替换
heLLo,worLd!

>>>s.replace(l,L,2)#给出合理的次数,就只替换count个
heLLo,world!

‘‘‘
当count=0时,返回原字符串,当为复数或者大于子串的总个数时,全部替换
‘‘‘
>>>s = "hello,world!"

#指定多个单字符进行替换,s.translate(table[,deleter])
‘’‘
先建立映射关系table,需导入string模块
’‘’
>>>import string
>>>table = string.maketrans(hel,123)#两个参数一一对应
>>>s.translate(table)#按映射关系,进行替换
1233o,wor3d!

>>>s.translate(table,l)#给出要从s中删除的单字符连起来的字符串,先删后替换
120,word!

9.连接

s1 = "hello"
se = "world!‘
arg = (s1,s2)
>>>,.join(arg)
hello,world!

‘’‘
str.join(squence):参数是列表或者元组,用str将参数中的元素按顺序连接起来
此方法比+效率高些
’‘’

10、格式化

 

#格式化有两种方式,%和str.format()方法,推荐使用内置方法

>>>s1,s2 = Hanmeimei,apple
>>>{} love {}..format(s1,s2)#按顺序一一对应
hanmeimei love apple.
>>>{} love {}..format(s2,s1)
apple love hanmeimei.

>>>{0} love {1}..format(s1,s2)#按索引号一一对应
hanmeimei love apple.
>>>{1} love {2}..format(s2,s1)
apple love hanmeimei.

#可以接受列表,元组作为参数进行格式化
l = [s1,s2]
>>>{} love {}..format(*l)#一一对应
hanmeimei love apple.
>>>{1} love {0}..format(*l)#一一对应
apple love hanmeimei.

#对于多个参数来说,下面的方法可靠性高
>>>{name} love {fruit}..format(name = lilei,fruit = apple)
lilei love apple.

>>>d = {name:lilei,fruit:apple}#将字典作为参数进行格式化
>>>{name} love {fruit}..format(**d)
lilei love apple.

>>>class Plant(object):#还可以对类进行格式化
    type = tree
    kinds = [{name: oak}, {name: maple}]
...

>>>{p.type}: {p.kinds[0][name]}.format(p=Plant())
tree: oak

#格式化有两种方式,%和str.format()方法,推荐使用内置方法

>>>s1,s2 = Hanmeimei,apple
>>>{} love {}..format(s1,s2)#按顺序一一对应
hanmeimei love apple.
>>>{} love {}..format(s2,s1)
apple love hanmeimei.

>>>{0} love {1}..format(s1,s2)#按索引号一一对应
hanmeimei love apple.
>>>{1} love {2}..format(s2,s1)
apple love hanmeimei.

#可以接受列表,元组作为参数进行格式化
l = [s1,s2]
>>>{} love {}..format(*l)#一一对应
hanmeimei love apple.
>>>{1} love {0}..format(*l)#一一对应
apple love hanmeimei.

#对于多个参数来说,下面的方法可靠性高
>>>{name} love {fruit}..format(name = lilei,fruit = apple)
lilei love apple.

>>>d = {name:lilei,fruit:apple}#将字典作为参数进行格式化
>>>{name} love {fruit}..format(**d)
lilei love apple.

>>>class Plant(object):#还可以对类进行格式化
    type = tree
    kinds = [{name: oak}, {name: maple}]
...

>>>{p.type}: {p.kinds[0][name]}.format(p=Plant())
tree: oak


‘’‘
冒号:字符位数声明、空白自动填补符 的声明、千分位的声明、变量类型的声明: 字符串s、数字d、浮点数f 、对齐方向符号 < ^ >
’‘’
>>>{:.5}.format(xylophone)#截取长度为5的子串,小于5返回原字符串
xylop
        

>>>{:^10}.format(test)#长度为10,字符串居中,字符串长度大于10,返回本身
   test   
 
>>>{:.{}}.format(xylophone, 7)#指定长度
xylopho

>>>{:4d}.format(42)#指定数字长度,位数不够默认空格;长度大于4,返回本身
  42

>>>{:06.2f}.format(3.141592653589793)#位数不够,用0填充,小数点前指定总长度,小数点后指定小数位数
003.14
 
>>>{:+d}.format(42)#显示指定的一元操作符
+42
 
‘‘‘
千分位、浮点数、填充字符、对齐的组合使用:
:冒号+空白填充+右对齐+固定宽度18+浮点精度.2+浮点数声明f
>>>‘{:>18,.2f}‘.format(70305084.0)
‘     70,305,084.00‘

#惊叹号!限定访问__repr__等魔法函数:
>>>class Data(object):

    def __str__(self):
        return ‘str‘

    def __repr__(self):
        return ‘repr‘

...

>>>‘%s %r‘ % (Data(), Data())
str repr
>>>‘{0!s} {0!r}‘.format(Data())
str repr

#{0!s}和{:xxxx}的__format__方法不能同时使用,python2测试,原因不详
‘‘‘
增加类魔法函数__format__(self, format) , 可以根据format前的字符串格式来定制不同的显示, 如: ’{:xxxx}’  此时xxxx会作为参数传入__format__函数中
‘‘‘

>>>class HAL9000(object):

    def __format__(self, format):
        if (format == ‘open-the-pod-bay-doors‘):
            return "I‘m afraid I can‘t do that."
        return ‘HAL 9000‘
...

>>>‘{:open-the-pod-bay-doors}‘.format(HAL9000())
I‘m afraid I can‘t do that.
 
#时间日期的特例:
>>>from datetime import datetime
>>>‘{:%Y-%m-%d %H:%M}‘.format(datetime(2001, 2, 3, 4, 5))
2001-02-03 04:05

#惊叹号!限定访问__repr__等魔法函数:
>>>class Data(object):

    def __str__(self):
        return ‘str‘

    def __repr__(self):
        return ‘repr‘

...

>>>‘%s %r‘ % (Data(), Data())
str repr
>>>‘{0!s} {0!r}‘.format(Data())
str repr

#{0!s}和{:xxxx}的__format__方法不能同时使用,python2测试,原因不详
‘‘‘
增加类魔法函数__format__(self, format) , 可以根据format前的字符串格式来定制不同的显示, 如: ’{:xxxx}’  此时xxxx会作为参数传入__format__函数中
‘‘‘

>>>class HAL9000(object):

    def __format__(self, format):
        if (format == ‘open-the-pod-bay-doors‘):
            return "I‘m afraid I can‘t do that."
        return ‘HAL 9000‘
...

>>>‘{:open-the-pod-bay-doors}‘.format(HAL9000())
I‘m afraid I can‘t do that.
 
#时间日期的特例:
>>>from datetime import datetime
>>>‘{:%Y-%m-%d %H:%M}‘.format(datetime(2001, 2, 3, 4, 5))
2001-02-03 04:05

 

python2:字符串方法

标签:open   self   映射   gets   浮点   填充   xxx   ndt   不能   

原文地址:http://www.cnblogs.com/Wolverine-python/p/7648189.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!