python输出格式化

作者: 西方失败9527 | 来源:发表于2019-04-06 09:34 被阅读0次

1)Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

2)相对于老版的%格式方法,它有很多优点:

1.在%方法中%s只能替代字符串类型,而在format中不需要理会数据类型;

2.单个参数可以多次输出,参数顺序可以不相同;

3.填充方式十分灵活,对齐方式十分强大;

4.官方推荐用的方式,%方式将会在后面的版本被淘汰。

实例1:

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序'hello world'

>>> "{0} {1}".format("hello", "world")  # 设置指定位置'hello world'

>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置'world hello world'

实例2:

#!/usr/bin/python

# -*- coding: UTF-8 -*- 

print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))

 # 通过字典设置参数

site = {"name": "菜鸟教程", "url": "www.runoob.com"}

print("网站名:{name}, 地址 {url}".format(**site)) 

# 通过列表索引设置参数

my_list = ['菜鸟教程', 'www.runoob.com']

print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必须的

实例3:

class AssignValue(object):

def __init__(self, value):

self.value =value

my_value = AssignValue(6)

print('value 为: {.value}'.format(my_value))# "0" 是可选的

数字格式化(略,用到时再行补充,博客只作为自身笔记,并未考虑他人查询,请恕罪)

相关文章

  • 实战

    python的格式化输出 #python格式化输出 ##%对于未知变量类型,用这样就不太方便了 name='lis...

  • 入门输入输出篇

    python 的输入和输出 输出 print('hello') 格式化输出: 命令行: >>> 'Hello, %...

  • Python2与Python3中print用法总结

    Python2中的print用法 在Python2 中 print 是一种输出语句 1.格式化输出整数 2.格式化...

  • Python 中的常见 格式化符号

    Python 认识格式化输出 中的 格式化符号 在前面的文章里我们早早就接触过Python中的输出的函数prinn...

  • python—输入与输出

    Python的格式化输出 使用字符串格式化的形式来优化Python的输出,使用%作为占位符。%后面跟的是变量的类型...

  • Python使用format与f-string数字格式化

    Python使用format与f-string数字格式化 输出:

  • python笔记

    Python format格式化输出 浅谈 Python 的 with 语句 Python中迭代原理生成器和迭代原...

  • python-print函数的使用

    1.格式化输出 看看《Python基础编程》中对格式化输出的总结: %字符:标记转换说明符的开始 转换标志:-表示...

  • Python自学笔记Day9

    Python自学笔记——Day9 基本输入输出 1. 输出函数及格式化 Python两种输出值的方式: 表达式语句...

  • Python几种格式化输出

    Python格式化输出 print(userInfo)print(userInfo1)print(userInfo...

网友评论

    本文标题:python输出格式化

    本文链接:https://www.haomeiwen.com/subject/yjnliqtx.html