您的位置:首页 > 编程语言 > Python开发

python学习 第三章 使用字符串 《python基础教程第二版修订版》

2017-01-21 19:52 351 查看
3.2字符串格式化:精简版

字符串格式化操作符-百分号%

>>> format = "Hello. %s. %s enough for ya?"
>>> values = ('wordl', 'Hot')
>>> print format % values
Hello. wordl. Hot enough for ya?


格式化浮点数

>>> format = "Pi with three decimals: %.3f"
>>> from math import pi
>>> print format % pi
Pi with three decimals: 3.142


模板字符串

>>> from string import Template
>>> s = Template('$x, glorious $x!')
>>> s.substitute(x='slurm')
'slurm, glorious slurm!'


>>> s = Template("It's ${x}tastic!")
>>> s.substitute(x = 'slurm')
"It's slurmtastic!"


>>> 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.'


方法sate_substitute不会因缺少值或者不正确使用$字符而出错

3.3 字符串格式化:完整版

>>> '%s plus %s equals %s' % (1, 1, 2)
'1 plus 1 equals 2'


基本的转换说明符包括以下部分:

1.%字符

2.转换标志:

- 左对齐

+ 转换前加正负号

”“空白字符 表示正数之前保留空格

0 表示转换值若位数不够则用0填充

3.最小字段宽度,如果是*,则宽度会从值元组中读出

4.点. 后跟精度值,如果是字符串, 表示最大字段宽度, 如果是*,则精度会从值元组中读出

5.转换类型

d, i 带符号的十进制整数

f, F 十进制浮点数

C 单字符,接受整数或者单字符字符串

s 字符串 使用str转换任意python对象

r 字符串 使用repr转换任意python对象

3.3.1 简单转换

>>> '%s plus %s equals %s' % (1, 1, 2)
'1 plus 1 equals 2'
>>> 'Price of eggs: $%d' % 42
'Price of eggs: $42'
>>> 'Hexadecimal price of eggs: %x' % 42
'Hexadecimal price of eggs: 2a'
>>> from math import pi
>>> 'pi: %f...' % pi
'pi: 3.141593...'
>>> 'Very inexact estimate of pi: %i' % pi
'Very inexact estimate of pi: 3'
>>> 'Using str: %s' % 42L
'Using str: 42'
>>> 'Using repr: %r' % 42L
'Using repr: 42L'


3.3.2 字符宽度和精度

>>> '%10f' % pi
'  3.141593'
>>> '%10.2f' % pi
'      3.14'
>>> '%.2f' % pi
'3.14'
>>> '%.5s' % 'Guido van Rossum'
'Guido'
>>> '%5s' % 'Guido van Rossum'
'Guido van Rossum'
>>> '%30s' % 'Guido van Rossum'
'              Guido van Rossum'
>>> '%.*s' % (5, 'Gudio can Rossum')
'Gudio'


字符串点前表示最大宽度,点后表示最小宽度

3.3.3 符号、对齐和用0填充

>>> '%010.2f' % pi
'0000003.14'
>>> '%-10.2f' % pi
'3.14
>>> print ('% 5d' % 10) + '\n' + ('%+5d' % -10)
10
-10
>>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10)
+10
-10


字符串格式化实例

width = input("Please enter width: ")

price_width = 10
item_width = width - price_width

header_format = '%-*s%*s'
format = '%-*s%*.2f'

print '=' * width

print header_format % (item_width, 'Item', price_width, 'Price')

print '-' * width

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

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.00
===================================


3.4字符串方法

3.4.1 find

在一个较长的字符串中查找子串,返回子串所在位置的最左端索引,如果没有找到则返回-1

>>> 'With a moo-moo here. and a moo-moo there'.find('moo')
7
>>> title = "Monty Python's Flying Circus"
>>> title.find('Monty')
0
>>> title.find('Python')
6
>>> title.find('Flying')
15
>>> title.find('Zirquss')
-1
>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$', 1)
20
>>> subject.find('!!!')
16
>>> subject.find('!!!', 0, 16)
-1


3.4.2join

split方法的逆方法,用来连接序列中的元素

>>> seq = ['1', '2', '3', '4', '5']
>>> sep = '+'
>>> sep.join(seq)
'1+2+3+4+5'


3.4.3 lower

返回字符串的小写字母版

>>> name = 'Gumby'
>>> names = ['gumby', 'smith', 'jones']
>>> if name.lower() in names : print 'Fount it!'

Fount it!


和lower方法相关的是title方法,它会将字符串转会为标题,也就是所有单词的首字母大写,而其他字母小写

>>> "that's all folks".title()
"That'S All Folks"
>>> import string
>>> string.capwords("that's all folks")
"That's All Folks"


string模块的capwords函数有相同功能

3.4.4replace

返回某字符串的所有匹配项均被替换之后得到字符串

>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'


3.4.5split

jion的逆方法,用来将字符串分割成序列

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']


3.4.6strip

返回去除两侧空格的字符串

>>> '       internal whitespace is kept      '.strip()
'internal whitespace is kept'


>>> names = ['gumby', 'smith', 'jones']
>>> name = 'gumby '
>>> if name.strip() in names : print 'Found it!'

Found it!


也可以指定需要去除的字符,将他们列为参数即可

>>> '*** SPAM * for * everyone!!!***'.strip('*!')
' SPAM * for * everyone'


3.4.7translate

可以替换字符串中的某些部分,但只处理单个字符,可以同时进行多个替换

转换钱需要先完成一张转换表,用string模块中的maketrans

>>> from string import maketrans
>>> table = maketrans('cs', 'kz')
>>> len(table)
256
>>> table[97:123]
'abkdefghijklmnopqrztuvwxyz'
>>> maketrans('','')[97:123]
'abcdefghijklmnopqrstuvwxyz'
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'


translate的第二个参数是可选的,用来指定需要删除的字符

>>> 'this is an incredible test'.translate(table, ' ')
'thizizaninkredibletezt'


2017.1.21
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python