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程序的组成 表达式:建立并且处理数据对象且能返回数据对象的引用关系 示例:1 + 2 系统会产生1和2俩个对象,并且进行处理生产对象3,将对象3返回回去。 二、核心的...

python生成随机红包的实例写法

假设红包金额为money,数量是num,并且红包金额money>=num*0.01 原理如下,从1~money*100的数的集合中,随机抽取num-1个数,然后对这些数进行排序,在...

Pandas读写CSV文件的方法示例

Pandas读写CSV文件的方法示例

读csv 使用pandas读取 import pandas as pd import csv if name == '__main__': # header=0——表示csv文件的...

Python 实现输入任意多个数,并计算其平均值的例子

学习了Python相关数据类型,函数的知识后,利用字符串的分割实现了输入任意多个数据,并计算其平均值的小程序。思路是接收输入的字符串,以空格为分隔符,将分割的数据存入列表(lst1)中,...

python利用datetime模块计算时间差

今天写了点东西,要计算时间差,我记得去年写过,于是今天再次mark一下,以免自己忘记 In [27]: from datetime import datetime In [28]:...