zoukankan      html  css  js  c++  java
  • 【python学习笔记】字符串格式化

    # 字符串格式化
    '''
    {参数序号:格式控制标记}
    填充 对齐(< > ^) 宽度 逗号 精度 类型
    
    '''
    a = "hello"
    b = "world"
    print("{},{}".format(a, b))
    print("{1},{0}".format(a, b))
    
    # 填充
    s = "hello"
    print("{0:*^20} world!".format(s))
    
    # 千位逗号
    print("{:,}".format(1234567890))
    
    # 精度
    print("{:.2f}".format(1234.56789))
    print("{:.5}".format("hello, world!"))
    
    # 类型
    print("{0:b},{0:d},{0:x},{0:X},{0:c}".format(425))
    print("{0:c}".format(98))

     

    练习题:

    # 统计英文文章中单词出现的频率
    wordstring = '''
    it was the best of times it was the worst of times.
    it was the age of wisdom it was the age of foolishness.
    '''
    # 替换标点符号
    wordstring = wordstring.replace('.',' ')
    
    # 分割单词
    wordlist = wordstring.split()
    print(wordlist)
    
    # 统计次数
    wordfreq = []
    for w in wordlist:
        wordfreq.append(wordlist.count(w)) # append函数返回None
    
    # 字典格式输出单词出现的频率
    f = dict(zip(wordlist, wordfreq))
    print(f)

    # 字符串格式化
    s = 'python'
    print("{0:3}".format(s)) # 参数序号,格式控制符
    
    # 长字符串
    print('''
    唐诗
    
    宋词
    ''')
    
    # 原始字符串
    print(r'''
    唐诗
    
    宋词
    ''')

     

  • 相关阅读:
    Mybatis与Hibernate概述
    Linux命令中:rsync和scp之间的区别
    更改了ssh文件下,还没有权限
    karaf 控制台 常用linux指令(2)
    karaf 控制台 常用linux指令(1)
    POM文件详解(2)
    POM文件详解(1)
    maven配置parent pom查找策略
    排序算法性能比较
    Eclipse下用NDK编译生成so文件
  • 原文地址:https://www.cnblogs.com/zhaoyujiao/p/15346178.html
Copyright © 2011-2022 走看看