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

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

2013-05-24 20:15 387 查看

从链表到字符串

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