【语言处理与Python】3.9格式化:从链表到字符串

从链表到字符串
silly=['We', 'called', 'him', 'Tortoise', 'because', 'he', 'taught', 'us', '.']

‘ ’.join(silly)

'We calledhim Tortoisebecausehetaught us.’#join()方法适合于一个字符串的链表

 

字符串与格式
#字符串格式化表达式

for word in fdist:

print ‘%s->%d;’%(word,fdist[word])

#也可以使用模版

template = 'Lee wantsa %sright now'

menu= ['sandwich', 'spam fritter', 'pancake']

for snack in menu:

print template %snack

 

排列
#设置宽度

'%6s' %'dog'

width=6

'%-*s' %(width, 'dog')

width=max(len(w) for w in words)

 

将结果写入文件
output_file=open(‘output.txt’,w)

words=set(nltk.corpus.genesis.words(‘english-kjv.txt’))

for word in sorted(words):

output_file.write(word+’\n’)

 

文本换行

有的时候,需要采取自动换行

from textwrap import fill

format=’%s(%d)’

pieces=[format % (word,len(word)) for word in saying]

output=’ ’.join(pieces)

wrapped=fill(output)

print wrapped

 

转载于:https://www.cnblogs.com/createMoMo/archive/2013/05/24/3097530.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值