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

yipeiwu_com6年前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使用jsonpath-rw模块处理Json对象操作示例

本文实例讲述了Python使用jsonpath-rw模块处理Json对象操作。分享给大家供大家参考,具体如下: 这两天在写一个爬虫,需要从网站返回的json数据提取一些有用的数据。 向u...

详解python基础之while循环及if判断

 wlile循环   while True表示永远为真,不管是什么条件都会向下执行,下面是写的一个例子。 #!/usr/bin/env python age = 24        ...

python 缺失值处理的方法(Imputation)

一、缺失值的处理方法 由于各种各样的原因,真实世界中的许多数据集都包含缺失数据,这些数据经常被编码成空格、nans或者是其他的占位符。但是这样的数据集并不能被scikit - learn...

浅析python3字符串格式化format()函数的简单用法

 format()函数 """ 测试 format()函数 """ def testFormat(): # format()函数中有几个元素,前面格式化的字符串中就要有...

使用Python对微信好友进行数据分析

使用Python对微信好友进行数据分析

1、准备工作 1.1 库介绍 只有登录微信才能获取到微信好友的信息,本文采用wxpy该第三方库进行微信的登录以及信息的获取。 wxpy 在 itchat 的基础上,通过大量接口优化提升了...