• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python中字符串的格式化方法小结

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

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了python字符串方法,python中字符串的方法,python字符串处理,python 字符串,python 字符串转数字等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

老办法

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

格式化浮点数:

pi = 3.14159
print(" pi = %1.2f ", % pi)
</div>


多个替换值:

s1 = "cats"
s2 = "dogs"
s3 = " %s and %s living together" % (s1, s2)
</div>

没有足够的参数:

使用老的格式化方法,我经常犯错"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)
</div>

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

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

</div>

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

</div>


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])
</div>

</div>

您可能想查找下面的文章:

  • Python中的字符串查找操作方法总结
  • Python中字符串的格式化方法小结
  • Python中字符串的格式化方法小结
  • python连接字符串的方法小结
  • python字符串对其居中显示的方法
  • python连接字符串的方法小结
  • python字符串对其居中显示的方法
  • python保存字符串到文件的方法
  • Python合并字符串的3种方法
  • Python中字符串对齐方法介绍

相关文章

  • Windows系统下使用flup搭建Nginx和Python环境的方法
  • Python自动化构建工具scons使用入门笔记
  • python进阶教程之循环对象
  • 用Python从零实现贝叶斯分类器的机器学习的教程
  • Pthon批量处理将pdb文件生成dssp文件
  • 举例讲解Python设计模式编程中的访问者与观察者模式
  • Python模块学习 re 正则表达式
  • python笔记(1) 关于我们应不应该继续学习python
  • Python中列表、字典、元组、集合数据结构整理
  • Python处理JSON时的值报错及编码报错的两则解决实录

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • python中字符串类型json操作的注意事项
    • 解决Python中字符串和数字拼接报错的方法
    • python获取本机mac地址和ip地址的方法
    • python中enumerate函数遍历元素用法分析
    • Python实现的数据结构与算法之链表详解
    • Django中对通过测试的用户进行限制访问的方法
    • wxpython中利用线程防止假死的实现方法
    • 使用Python的PEAK来适配协议的教程
    • Python多线程实现同步的四种方式
    • python批量提取word内信息

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有