Python中字符串的格式化方法小结

yipeiwu_com5年前Python基础

老办法

Python2.6之前,格式字符串的使用方法相对更简单些,虽然其能够接收的参数数量有限制。这些方法在Python3.3中仍然有效,但已有含蓄的警告称将完全淘汰这些方法,目前还没有明确的时间进度表。

格式化浮点数:

pi = 3.14159
print(" pi = %1.2f ", % pi)


多个替换值:

s1 = "cats"
s2 = "dogs"
s3 = " %s and %s living together" % (s1, s2)

没有足够的参数:

使用老的格式化方法,我经常犯错"TypeError: not enough arguments for formating string",因为我数错了替换变量的数量,编写如下这样的代码很容易漏掉变量。

set = (%s, %s, %s, %s, %s, %s, %s, %s) " % (a,b,c,d,e,f,g,h,i)

对于新的Python格式字符串,可以使用编号的参数,这样你就不需要统计有多少个参数。

set = set = " ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}) ".format(a,b,c,d,e,f,g)

Python 2.x 基于字典字符串格式化

"%(n)d %(x)s" %{"n":1, "x":"spam"}
reply = """
Greetings...
Hello %(name)s!
Your age squared is %(age)s
"""
values = {'name':'Bob', 'age':40}
print rely % values


Python 3.x format方法格式化

template = '{0},{1} and {2}'
template.format('spam','ham','eggs')

template = '{motto}, {pork} and {food}'
template.format(motto='spam', pork='ham', food='eggs')

template = '{motto}, {0} and {food}'
template.format('ham', motto='spam', food='eggs')

'{motto}, {0} and {food}'.format(42, motto=3.14, food=[1,2,3])

相关文章

Python 仅获取响应头, 不获取实体的实例

Python 仅获取响应头, 不获取实体的实例

Python Just get Response Headers, not get content. 1. Use HEAD method >>> import r...

Python+OpenCV目标跟踪实现基本的运动检测

Python+OpenCV目标跟踪实现基本的运动检测

目标跟踪是对摄像头视频中的移动目标进行定位的过程,有着非常广泛的应用。实时目标跟踪是许多计算机视觉应用的重要任务,如监控、基于感知的用户界面、增强现实、基于对象的视频压缩以及辅助驾驶等。...

PyQt5实现从主窗口打开子窗口的方法

PyQt5实现从主窗口打开子窗口的方法

1.在Qt Designer中设计两个简单窗口 2.将.ui文件转换成.py文件 3.新建**.py文件 #-*- coding:utf-8 -*- from PyQt5.QtWi...

Python根据指定日期计算后n天,前n天是哪一天的方法

本文实例讲述了Python根据指定日期计算后n天,前n天是哪一天的方法。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #!/usr/bin/pyth...

全面了解Python环境配置及项目建立

全面了解Python环境配置及项目建立

一、安装Python Python比较稳定的两个版本是Python 3.5和Python 2.7,我用的是Python 2.7,下载地址是:https://www.python.org/...