字符串和字典格式化
字符串
字符串格式化:%s(轉(zhuǎn)換說明符)
當(dāng)要字符串中含有%条霜,使用%%代替。
>>>format="Hello, %s. %s enough for ya?"
>>>value=('world', 'Hot')
>>>print format % value
Hello, world. Hot enough for ya?
實(shí)數(shù)/字段寬度精度格式化:%其他字段寬度(向右對(duì)齊).想保留的小數(shù)位數(shù)/精度)f(實(shí)數(shù))/s(字段)
想保留的小數(shù)位數(shù)/精度可以用代替碌尔,然后再% 后和格式化的字段用元祖形式表示。(精度, 字段)
字段寬度也可以用代替赌髓,然后再% 后和格式化的字段用元祖形式表示祝钢。(寬度, 字段)
其他:
0:位數(shù)不夠0填充;-:左對(duì)齊吱窝;+:帶正負(fù)號(hào)讥邻;" " 空白字符:正數(shù)前保留字符。
>>>format="Pi with three decimals: %.3f"
>>>from math import pi
>>>print format % pi
Pi with three decimals:3.142
模板字符串: string模塊中的template
當(dāng)要字符串中含有$院峡,使用$$代替兴使。
>>>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.'
練習(xí): 打印根據(jù)用戶輸入寬度的價(jià)目表
#-*- coding:utf8 -*-
#使用給定的寬度打印格式化后的價(jià)格列表
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
方法:
- find(要查找的字符串, 起點(diǎn)索引,終點(diǎn)索引): 查找子字符串的第一個(gè)索引,返回索引位置照激,未找到返回-1发魄。 當(dāng)起點(diǎn),終點(diǎn)都填時(shí)俩垃,包含起點(diǎn)励幼,不包含終點(diǎn)
- join(要join的字符串列表): 將要join的字符串列表用對(duì)象拼接起來,返回連接后的新字符串口柳。
- split(分隔符):join的逆方法苹粟,將字符串以分隔符分隔,返回分隔后的新字符串列表
- lower(為空):返回字符串小寫版跃闹,返回新字符串嵌削。單詞首字母大寫:title(), string.capwords(字符串)
- replace(要替換的字符串,目標(biāo)字符串):將要替換的字符串換成目標(biāo)字符串辣卒,返回新字符串掷贾。
- strip(指定去除的符號(hào),為空時(shí)去除空格):去除兩側(cè)(不含內(nèi)部)的所有指定符號(hào)荣茫,返回新的字符串
7.translate(替換標(biāo)準(zhǔn),需刪除字符):結(jié)合string.maketrans創(chuàng)建轉(zhuǎn)換表進(jìn)行批量替換想帅。
>>>from string import maketrans
>>>table=maketrans('cs', 'kz')
>>>’this is an incredible test'.translate(table,' ')
'thizizaninkredibletezt'
字典
可以直接 %(鍵) %(字典名) 這樣獲得了鍵對(duì)應(yīng)值
應(yīng)用到html很實(shí)用~ 簡(jiǎn)直特別實(shí)用
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
結(jié)果:
<html>
<head><title>My home page</title></head>
<body>
<h1>My home page</h1>
<p>Welcome to my home page!</p>
</body>