zoukankan      html  css  js  c++  java
  • 【语言处理与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
  • 相关阅读:
    Git 分支管理
    Git 保存工作区
    Git 版本控制
    Git 基本命令-详细版本
    Git 初始化配置
    Git 基本概念:分区
    JavaScript 调试
    JavaScript 错误
    JS 判断字符串是否全部为字母
    JS 判断输入字符串是否为数字、字母、下划线组成
  • 原文地址:https://www.cnblogs.com/createMoMo/p/3097530.html
Copyright © 2011-2022 走看看