python基础教程笔记(chapt.3&4) 字符串和

2017-10-23  本文已影响6人  JuneZhu_870a

字符串和字典格式化

字符串

字符串格式化:%s(转换说明符)
当要字符串中含有%,使用%%代替。

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

实数/字段宽度精度格式化:%其他字段宽度(向右对齐).想保留的小数位数/精度)f(实数)/s(字段)
想保留的小数位数/精度可以用代替,然后再% 后和格式化的字段用元祖形式表示。(精度, 字段)
字段宽度也可以用
代替,然后再% 后和格式化的字段用元祖形式表示。(宽度, 字段)
其他:
0:位数不够0填充;-:左对齐;+:带正负号;" " 空白字符:正数前保留字符。

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

模板字符串: string模块中的template
当要字符串中含有$,使用$$代替。

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

练习: 打印根据用户输入宽度的价目表

#-*- coding:utf8 -*-
#使用给定的宽度打印格式化后的价格列表

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 % (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

方法:

  1. find(要查找的字符串, 起点索引,终点索引): 查找子字符串的第一个索引,返回索引位置,未找到返回-1。 当起点,终点都填时,包含起点,不包含终点
  2. join(要join的字符串列表): 将要join的字符串列表用对象拼接起来,返回连接后的新字符串。
  3. split(分隔符):join的逆方法,将字符串以分隔符分隔,返回分隔后的新字符串列表
  4. lower(为空):返回字符串小写版,返回新字符串。单词首字母大写:title(), string.capwords(字符串)
  5. replace(要替换的字符串,目标字符串):将要替换的字符串换成目标字符串,返回新字符串。
  6. strip(指定去除的符号,为空时去除空格):去除两侧(不含内部)的所有指定符号,返回新的字符串
    7.translate(替换标准,需删除字符):结合string.maketrans创建转换表进行批量替换。
>>>from string import maketrans
>>>table=maketrans('cs', 'kz')
>>>’this is an incredible test'.translate(table,' ')
'thizizaninkredibletezt'
字典

可以直接 %(键) %(字典名) 这样获得了键对应值
应用到html很实用~ 简直特别实用

data={'title':'My home page','text':'Welcome to my home page!'}
template='''<html>
<head><title>%(title)s</title></head>
<body>
<h1>%(title)s</h1>
<p>%(text)s</p>
</body>'''
print template % data
结果: 
<html>
<head><title>My home page</title></head>
<body>
<h1>My home page</h1>
<p>Welcome to my home page!</p>
</body>
上一篇下一篇

猜你喜欢

热点阅读