Python中格式化输出的两种方法介绍

不言
不言 原创
2018-09-26 16:06:35 3061浏览

本篇文章给大家带来的内容是关于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.

以上就是Python中格式化输出的两种方法介绍的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。