zoukankan      html  css  js  c++  java
  • Python学习 :格式化输出

    方式一:使用占位符 %

    常用占位符:% s   (s = string 字符串)
              % d   (d = digit 整数(十进制))
            %  f   ( f = float  浮点数

    name = input("请输入你的名字:")
    age = input("请输入你的年龄:")
    job = input("请输入你的职业:")
    salary = input("请输入你的薪酬:")
    
    if salary.isdigit():  #输入的数据是否像数字
        salary = int(salary)
    else :
        exit("请输入正确的数字")
        # 如果输入的不是数字将会退出程序
        
    # '''  三引号可以用于插入数据
    info = '''
    ---------- info of %s ----------
    姓名:%s
    年龄:%s
    职业:%s
    薪酬:%s
    -------------------------------
    ''' % (name, name, age, job, salary)
    
    print(info)
    

    方式二:format()函数(推荐使用)

    format()函数通过传入的字符串作为参数,并使用{}大括号作为占位符

    format(a , b) 变量a 对应{0}  变量b 对应{1}

    注意:Python从0开始计数,意味着索引中的第一位是0,第二位是1

    位置的匹配:
          (1)不带编号,即“{}”
          (2)带数字编号,可调换顺序,即“{0}”、“{1}”
          (3)带关键字,即“{a}”、“{b}”(需要设置关键字对应的字符串)

    age = 20
    name = 'ALEX'
    print('{1} is {0} years old' .format(age,name))
    print('{b} is {a} years old' .format(a = age, b = name))
    >>> ALEX is 20 years old
        ALEX is 20 years old
    

    format()可以指定格式,让输出的结果符合指定的样式

    一些符号的含义:

             {0}        —— { 0 }      表示第一个位置

             {0:10}   —— { :10}    表示有10个字符那么长并且左对齐(默认为左对齐)

             {0:>15} ——{ :>15}  表示有15个字符那么长并且右对齐

             {0:.2}     ——{ : .2}    表示对于传入的字符串,截取前两个字符

             {0:^}     —— {: ^}     表示放到该位置的字符串要居中

             {0:d}      —— {0:d}    表示需要在这个位置放一个整数(数字默认状态下为右对齐)

             {0:f}       —— {0:f}    表示需要在这个位置放一个浮点数(数字默认状态下为右对齐)

    a = " I  love {0:10} and {1:10}. ".format("sing","dance")
    # 左对齐,字符串的长度为10个字符
    print(a)
    >>> I  love sing       and dance    .
    a = " I  love {0:^10.3} and {1:^10.3}. ".format("sing","dance")
    # 居中,字符串的长度为10个字符,截取前三个字符
    print(a)
    >>> I  love    sin      and    dan    .   
    age = 28
    weight = 70.423
    print("Alex is {0} years old and his weights is {1:.2f} kg." . format(age,weight))
    # 浮点数需要保留两位小数
    >>> Alex is 28 years old and his weights is 70.42 kg.
    
  • 相关阅读:
    常见的五种App开发模式
    iOS提供的实用的属性和方法
    iOS开发思想
    iOS函数式编程
    iOS链式编程范例
    ios不起眼的错误
    iOS将汉字转成拼音
    ReactiveCocoa
    LuaViewSDK
    pycharm配置qtdesigner
  • 原文地址:https://www.cnblogs.com/ArticleYeung/p/9702679.html
Copyright © 2011-2022 走看看