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

python学习之字符串(下)

时间:2015-12-28 23:39:15      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

----------------------------------------------
实际应用中的其他常见的字符串方法

>>>line = "the knights who say ni!\n"
>>>line.restrip();   清楚末尾的空格
the knights who say ni!
>>>line.upper()   大小写转换
THE KNIGHTS WHO SAY NI!\n
>>>line.isalpha()    isalpha() 方法检测字符串是否只由字母组成。
false
>>>line.endswith(‘ni!\n‘)   检测字符串是否以ni结尾
true
>>>line.startswitch(‘the‘)  检测字符串是否以the 开头
true

>>>line.find(‘ni‘)!=-1     字符检测
true
>>>‘ni‘in line
true
>>> sub = ‘ni\n‘
line.endswitch(sub)
true
>>>line[-line(sub):]==sub
true

--------------------------------------------
字符串格式代码已经在前面说过了就不写例子了
字符串格式化代码
s     字符串
r     s 但是使用repr  不是str
c    字符
d     十进制
i    整数
u    无符号整数
o    八进制整数
x    十六进制这人你高数
e    浮点指数
f    浮点十进制
g    浮点e或f
%    常量%


基于字典的字符串格式化
字符串格式化同时也允许左边的转换目标来引用右边字典中的键来提取对应的值

>>>‘%(n)d %(x)s‘ %{"n":1,"x":"spam"}
‘1 spam‘

>>>food = ‘spam‘
>>>age = 40
>>var()
{‘food‘:‘spam‘,‘age‘:40}


>>>"%(age)d %(food)s" %var()
‘40 spam‘


字符串格式化之左对齐和右对齐

>>>‘{0:10} = {1:10}‘.format(‘spam‘,123.4567)
‘spam       =    123.4567‘
>>>‘{0:>10} = {1:<10}‘.format(‘spam‘,123.4567)
‘      spam = 123.4567  ‘
>>>‘{0[‘platform‘]:>10} = {1[item]:<10}‘.format({‘platform‘:‘spam‘},dict(item = 123.4567));

‘      spam =    123.4567‘


格式化方法同样可以支持十六进制八进制和二进制
>>>‘{0:x},{1:o},{2:b}‘.format(255,255,255)
‘FF,277,11111111‘

>>>‘{0:.2f}‘.format(1/3.0)
‘0.33‘
>>>‘%.2f‘% (1/3.0)
‘0.33‘

python学习之字符串(下)

标签:

原文地址:http://www.cnblogs.com/techdreaming/p/5084220.html

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