博客
关于我
[转]Python中format( )用法
阅读量:580 次
发布时间:2019-03-07

本文共 1294 字,大约阅读时间需要 4 分钟。

Python 的字符串格式化功能自 2.6 版本后引入了更强大的语法,取代了传统的 % 格式符,通过 {}: 来实现更灵活的格式化需求。本文将详细介绍如何利用这些语法特性提升代码的可读性和效率。

1. 基本语法

Python 的字符串格式化使用 format 方法,接受任意数量的参数,可通过位置、关键字或对象属性指定替换位置。这种机制打破了传统的按顺序传递参数的局限性。

通过位置

'In [1]: ${0},{1}'.format('kzc', 18)'Out[1]: kzc,18'
'In [2]: ${},{='.format('kzc', 18)'Out[3]: kzc,18'
'In [3]: '{1},{0},{1}'.format('kzc', 18)'Out[3]: 18,kzc,18'

通过关键字参数

'In [5]: '{name},{age}'.format(age=18, name='kzc')'Out[5]: kzc,18'

通过对象属性

class Person:    def __init__(self, name, age):        self.name = name        self.age = age    def __str__(self):        return 'This guy is {self.name},is {self.age} old'.format(self=self)
'In [2]: str(Person('kzc', 18))'Out[2]: This guy is kzc, is 18 old'

通过下标

p = ['kzc', 18]'In [7]: '{0[0]},{0[1]}'.format(p)'Out[7]: kzc,18'

这些"映射"方式赋予了开发者更多的灵活性,尤其是在处理列表、元组和字典时,能够以更加简洁的方式传递数据。

2. 格式限定符

格式化字符串可以使用特殊字符来定制输出格式。这些字符通常以 : 符号后跟填充字符和对齐方式。

填充与对齐

  • 填充字符可以是任意单个字符,默认为空格。
  • 对齐方式包括:
    • ^:居中对齐
    • <:左对齐
    • >:右对齐
    • :0:左对齐并且用空格填充至指定宽度

示例

'In [15]: '{: >8}'.format('189')'Out[15]:   189'
'In [16]: '{:0>8}'.format('189')'Out[16]: 00000189'
'In [17]: '{:a>8}'.format('189')'Out[17]: aaaaa189'

精度与类型

  • 使用 . 后跟格式字符,可以指定精度和类型。
  • 常用类型:
    • f:浮点数
    • d:整数
    • o:八进制
    • b:二进制
    • x:十六进制

金额格式化

'In [47]: '{:,}'.format(1234567890)'Out[47]: 1,234,567,890'

Python 的这种灵活性不仅适用于字符串格式化,还可以用于数值输出,能够显著提升代码的可维护性和阅读性。

转载地址:http://ycejz.baihongyu.com/

你可能感兴趣的文章
org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugManifest'
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.amqp.AmqpConnectException:java.net.ConnectException:Connection timed out:connect
查看>>
org.springframework.beans.factory.BeanDefinitionStoreException
查看>>
org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
查看>>
org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>