• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-07) 15次浏览 已收录 0个评论

这篇文章主要介绍了Python中字符串的格式化方法小结,提到了针对Python2.x与3.x版本相异情况下的不同技巧,需要的朋友可以参考下

老办法

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

格式化浮点数:

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

多个替换值:

 s1 = "cats" s2 = "dogs" s3 = <i style="color:transparent">来源gaodai$ma#com搞$代*码*网</i>" %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中字符串的格式化方法小结的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python中字符串的格式化方法小结

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址