zoukankan      html  css  js  c++  java
  • Python控制台打印的方式

    (1)正常打印

    print('abc')
    
    abc
    

    (2)加号拼接
    加号拼接仅限于字符串,若是其他类型,如数字,元组等,则会报错

    print('abc' + 'xxx')
    
    abcxxx
    

    错误案例:

    print('abc' + 1)
        print('abc' + 1)
    TypeError: can only concatenate str (not "int") to str
    

    (3)百分号打印
    这种方式是仿照C语言的方式 https://www.cnblogs.com/jixiaohua/p/11070772.html,使用占位符

    a = 1
    b = 2
    print("a + b = %d
    " % (a + b));
    
    a + b = 3
    

    PS:

    百分号%表示占位符,在后续通过%传入真实的值,如上述的 %(a+b)
    %s 拼接字符串,实际可以接受任何类型的值
    %d 只能拼接整数数字
    %.nf 四舍五入拼接浮点数,n表示保留到小数点后n位,不加.n默认保留6位小数
    %% 在有%拼接的的字符串里,如果要打印百分号,用两个百分号表示%%
    如果有多个%占位符,后面需要通过%元组形式传入多个值
    如果在%和拼接类型s、d、或者f等之间有用括号括起来的(变量名),则后面需要通过%字典形式赋值
    +m 右对齐共占m位,不足用空格填充,正数前面会加上正号+,负数前面会加上负号-
    -m 左对齐共占m位,不足用空格填充,正数前面无符号,负数前面会加上负号-

    (4)格式化模式
    Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。
    format 函数可以接受不限个参数,位置可以不按顺序。参考:https://www.runoob.com/python/att-string-format.html

    • 不设置指定位置,按默认顺序
    print("{} {}".format("hello", "world"))
    
    hello world
    
    • 设置指定位置
    print("{1} {0} {1}".format("hello", "world"))
    
    world hello world
    
    • 直接设置参数名称
    print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
    
    网站名:菜鸟教程, 地址 www.runoob.com
    
    • 通过字典设置参数
    site = {"name": "菜鸟教程", "url": "www.runoob.com"}
    print("网站名:{name}, 地址 {url}".format(**site))
    
    网站名:菜鸟教程, 地址 www.runoob.com
    
    • 通过列表索引设置参数
    my_list = ['菜鸟教程', 'www.runoob.com']
    
    # "0" 是必须的
    print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))
    
    网站名:菜鸟教程, 地址 www.runoob.com
    
    • 数字格式化
    print("{:.2f}".format(3.1415926))
    
    3.14
    

    以上就是Python中控制台打印的各种方式,而关于 print() 函数的各个参数的用法,可以参考:https://www.cnblogs.com/jiduxia/p/7492037.html

    参考文献
    菜鸟教程[https://www.runoob.com/python/att-string-format.html]
    博客园[https://www.cnblogs.com/jixiaohua/p/11070772.html]

  • 相关阅读:
    TeamViewer的替代品:realVNC
    Introduction of Generator in Python
    Excel: assign label to scatter chart using specific cell values
    reverse/inverse a mapping but with multiple values for each key
    虚拟化与云计算
    现代计算机简介
    CentOS 7 安装中网络设置111
    机械硬盘原理
    文件系统
    最重要的块设备——硬盘
  • 原文地址:https://www.cnblogs.com/dabenhou/p/15141569.html
Copyright © 2011-2022 走看看