`

python学习笔记4——第三章 字符串

 
阅读更多

第三章 字符串

 

1. 字符串不可修改,无法进行分片赋值

>>> print "Hello %s " %('test')   #%表示需替代的位置,s表示类型
Hello test 
>>> print "Hello %s" %'test'   #去掉括号也可
Hello test
>>> 

>>> print "Hell %%s %s" %'test'   #%%输出%
Hell %s test

>>> from math import pi
>>> print "Pi with three decimals: %.3f" %pi           #.3表示希望保留的小数位数,f表类型
Pi with three decimals: 3.142

 模板字符串  string--Template---substitute

>>> #模板字符串
>>> from string import Template
>>> s = Template('$x. glorious $x!')
>>> s.substitute(x='slurm')
'slurm. glorious slurm!'
>>> 
>>> #如果替换字段是单词的一部分,需要加{}
>>> s = Template("It's ${x}ful")
>>> s.substitute(x='beauti')
"It's beautiful"
>>> 
>>> #使用字典变量,提供值/名对
>>> s = Template("A $thing must never $action.")
>>> d = {}
>>> d['thing'] = 'gentleman'
>>> d['action'] = 'show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks.'
>>> 

 

2. 字符串格式化

 

(1)基本

>>> '%s plus %s equals %s' %(1, 1, 2)                #使用元组替代,注意不能丢掉括号
'1 plus 1 equals 2'

>>> 'Price of eggs: $%d' %42  # d 和 i 表带符号的十进制数
'Price of eggs: $42'
>>> 'Hexadecimal price of eggs $%x' %42  #x不带符号的十六进制(小写),X大写
'Hexadecimal price of eggs $2a'
>>> from math import pi
>>> 'Pi: %f...' %pi  #f/F十进制浮点数
'Pi: 3.141593...'
>>> 'Very inexact estimate of pi: %i' %pi #i带符号的十进制数
'Very inexact estimate of pi: 3'
>>> 'Using str: %s' %42L  #s字符串(str),r字符串(repr)
'Using str: 42'
>>> 'Using str: %r' %42L   #r字符串(repr)
'Using str: 42L'

 

(2)字段宽度和精度

>>> #宽度:转换后的值所保留的最小字符个数
>>> #精度:应包含的小数位数(数字),或转换后的最大字符个数(字符串)
>>> '%10f' %pi   #字段宽10
'  3.141593'
>>> '%10.2f' %pi #字段宽10,精度(小数位)2
'      3.14'
>>> '%.2f' %pi   #精度2
'3.14'
>>> '%.5s' % 'Hello world'  #精度5,对于字符串来说,就是最多五个字符
'Hello'
>>> '%.*s' % (5, 'Hello world')  #用*表示精度,值在元组中
'Hello'

 

(3)符号、对齐、0填充——在字段宽度和精度之前可放“标表”,该标表可以使0、+、-、空格

>>> '%010.2f' %pi  #0填充
'0000003.14'
>>> '%-10.2f' %pi  #左对齐
'3.14      '
>>> print('% 5d' %10) + '\n' + ('%5d' %-10)  #空格,在正数前加空白,方便与负数对齐,貌似不加也没问题??


   10
  -10
>>> print('%+5d' %10) + '\n' + ('%+5d' %-10)  #对正负数均标出符号
  +10

 

   完整示例

#使用给定的宽度打印格式化后的价格列表
width = input('Please enter width: ')
price_width = 10
item_width = width - price_width

header_format = '%-*s%*s'   #-左对齐,*宽度,s字符串
content_format = '%-*s%*.2f'

print '=' * width
print header_format %(item_width, 'Item', price_width, 'Price')
print '-' * width

print content_format %(item_width, 'Apples', price_width, 0.4)
print content_format %(item_width, 'Pears', price_width, 0.5)
print content_format %(item_width, 'Cantaloupes', price_width, 1.92)
print content_format %(item_width, 'Dried Apricots(16 oz.)', price_width, 8)
print content_format %(item_width, 'Prunes(4 lbs.)', price_width, 12.3333333)

print '=' * width

#运行结果
Please enter width: 35
===================================
Item                          Price
-----------------------------------
Apples                         0.40
Pears                          0.50
Cantaloupes                    1.92
Dried Apricots(16 oz.)         8.00
Prunes(4 lbs.)                12.33
===================================

 

3. 字符串方法

>>>#find()子串所在位置的最左端索引
>>> s = "Hello, how are you? Hello, I'm fine"
>>> s.find("Hello")         #in只能查找单个字符,而find可查找一个子串
0
>>> s.find("Hello", 1)     #提供查找的起始点
20
>>> s.find("you", 2, 16) #提供查找的起始点和结束点,其中包括起始索引,不包括结束索引
-1                                   #-1代表未找到
>>> s.find("you", 2, 20) #提供查找的起始点和结束点,其中包括起始索引,不包括结束索引
15

>>> #join()添加元素来连接列表,只能是字符串
>>> seq = ['1','2','3','4','5']
>>> joi = '+'
>>> joi.join(seq)
'1+2+3+4+5'
>>> 
>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> 


>>> #lower()返回字符串小写字母
>>> "I'M A DOCTOR!".lower()
"i'm a doctor!"
>>> 
>>> if 'GUMBY'.lower() in ['gumby', 'smith', 'jones']: print 'Found it!'
Found it!

>>> #title()单词首字母大写
>>> "that's all folks".title()
"That'S All Folks"
>>> 
>>> string模块的capwords()
>>> import string
>>> string.capwords("that's all, folks")
"That's All, Folks"

>>> #replace()替换
>>> 'This is a test'.replace('is', "isn't")
"Thisn't isn't a test"

>>> #split()分割,join()的逆方法
>>> 'Using the defalut'.split()
['Using', 'the', 'defalut']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']


>>> #strip()去除两侧空格
>>> "     Hello world   test   ".strip()
'Hello world   test'

>>> #也可指定需要去除的字符,将其列为参数即可,但是只去除两侧的字符
>>> '*** Hello * world ***!!!'.strip('*!')
' Hello * world '

#translate()同replace()一样,不过只能处理单个字符
#string模块中的maketrans()函数
>>> from string import maketrans
>>> table = maketrans('cs', 'kz')   #将c换为k,s换为z
>>> len(table)
256
>>> table[97:123]
'abkdefghijklmnopqrztuvwxyz'
>>> 'this is an incredible test'.translate(table)  #使用table作参数
'thiz iz an inkredible tezt'

 

总结:内容仍然简单,不过效率低,一点东西花了好长时间,需改善。

 

用到的函数

string.capsword(s[,seq])  #以seq分隔字符后,大写第一个字母,再用seq连接

string.maketrans(from, to)

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics