Python字符串

 python中的字符串取值

str = 'the world'

#取单词the, 和world
str[0:3] #the
str[4:]   #world

 

一些字符串处理

#字符串分割
string.split()
string.split(',')

#字符串去除空格
string.replace(' ', '')

#字符串去除尾部指定字符
string.strip()   #可用来去除空格,任意不需要的字符
string.lstrip()
string.rstrip()

#例子:
theString = 'saaaay yes no yaaaass'
print theString.strip('say') 
print theString.strip('say ') #say后面有空格 
print theString.lstrip('say') 
print theString.rstrip('say')
#结果###########
'''
yes no 
es no 
yes no yaaaass 
saaaay yes no
'''

 字符串一些格式转换

#如将数字2已02的形式转换成字符串
s = "%02d" %(2) 
print s

# 打印结果为: 02

 字符串格式化

day=20150101
hour=0
minute=0
print '{0}{1:0>2}{2:0>2}'.format(day, hour, minute)

#结果为:201501010000

数字     格式     输出     描述
3.1415926     {:.2f}     3.14     保留小数点后两位
3.1415926     {:+.2f}     +3.14     带符号保留小数点后两位
-1     {:+.2f}     -1.00     带符号保留小数点后两位
2.71828     {:.0f}     3     不带小数
5     {:0>2d}     05     数字补零 (填充左边, 宽度为2)
5     {:x<4d}     5xxx     数字补x (填充右边, 宽度为4)
10     {:x<4d}     10xx     数字补x (填充右边, 宽度为4)
1000000     {:,}     1,000,000     以逗号分隔的数字格式
0.25     {:.2%}     25.00%     百分比格式
1000000000     {:.2e}     1.00e+09     指数记法
13     {:10d}             13     右对齐 (默认, 宽度为10)
13     {:<10d}     13     左对齐 (宽度为10)
13     {:^10d}         13     中间对齐 (宽度为10)
 

 

 

posted on 2013-11-17 15:33  cfox  阅读(340)  评论(0编辑  收藏  举报

导航