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实现代码,供大家参考,具体内容如下 注意事项: 1、使用python3执行程序。按提示输入1或2,登录或退出程序 2、输入用户名后,如果用...

python logging 日志轮转文件不删除问题的解决方法

前言 最近在维护项目的python项目代码,项目使用了 python 的日志模块 logging, 设定了保存的日志数目, 不过没有生效,还要通过contab定时清理数据。 分析 项目使...

python多线程分块读取文件

本文实例为大家分享了python多线程分块读取文件的具体代码,供大家参考,具体内容如下 # _*_coding:utf-8_*_ import time, threading, C...

python定时检查某个进程是否已经关闭的方法

本文实例讲述了python定时检查某个进程是否已经关闭的方法。分享给大家供大家参考。具体如下: import threading import time import os impo...

python matplotlib中文显示参数设置解析

python matplotlib中文显示参数设置解析

最近在学习python著名的绘图包matplotlib时发现,有时候图例等设置无法正常显示中文,于是就想把这个问题解决了。 PS:本文仅针对Windows,其他平台仅供参考。 原因 大致...