Python format 函数- Python零基础入门教程 短命女 2022-10-12 12:55 245阅读 0赞 目录 * 一.format 函数简介 * 1.format 函数不设置下标 * 2.format 函数设置下标 * 二.format 函数实战 * 三.猜你喜欢 > 零基础 Python 学习路线推荐 : [Python 学习目录][Python] >> [Python 基础入门][Python 1] ## 一.format 函数简介 ## [format 函数][format]主要是用来构造字符串,基本语法是通过 \{\} 符号操作,并且每一个 \{\} 都可以设置顺序,分别与 format 的参数顺序对应,**如果没有设置\{\}下标,默认重 0 开始递增;** ### 1.format 函数不设置下标 ### # 不设置下标,两种方式等效 str = "{}{}{}{}".format(5,6,7,8) # {} 下标没有设置,默认为 0 ,1,2,3 str1 = "{0}{1}{2}{3}".format(5,6,7,8) \***\*如果没有设置\{\}下标,默认重 0 开始递增;\*\*** ### 2.format 函数设置下标 ### str2 = "{0}{0}{2}{3}".format(5,6,7,8) # {} 根据下标索引取值 str3 = "{3}{0}{2}{1}".format(5,6,7,8) **format 函数中的下标默认从 0 开始,对顺序没有限制,如果有设置下标,直接根据下标取值即可!** ## 二.format 函数实战 ## [Python][Python 2] 中 format 函数示例代码如下: # !usr/bin/env python # -*- coding:utf-8 _*- """ @Author:猿说编程 @Blog(个人博客地址): www.codersrc.com @File:format函数.py @Time:2021/3/17 20:37 @Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累! """ str = "{}{}{}{}".format(5,6,7,8) # {} 下标没有设置,默认为 0 ,1,2,3 str1 = "{0}{1}{2}{3}".format(5,6,7,8) str2 = "{0}{0}{2}{3}".format(5,6,7,8) # {} 根据下标索引取值 str3 = "{3}{0}{2}{1}".format(5,6,7,8) print(str) print(str1) print(str2) print(str3) ''' 输出结果: 5678 5678 5578 8576 ''' 很简单把,一看代码就明白,而且也不需要使用占位符,注意**format 函数**与\*\*[print 函数][print]\*\*的使用区别!! **注意:format 函数中的下标默认从 0 开始,对顺序没有限制。** ![5019994a6366d22ae2c56ecc9ab95f40.png][] ## 三.猜你喜欢 ## 1. [Python 简介][Python 3] 2. [Python Pycharm Anacanda 区别][Python Pycharm Anacanda] 3. [Python2.x 和 Python3.x,如何选择?][Python2.x _ Python3.x] 4. [Python 配置环境][Python 4] 5. [Python Hello World 入门][Python Hello World] 6. [Python 代码注释][Python 5] 7. [Python 中文编码][Python 6] 8. [Anaconda 是什么?Anconda 下载安装教程][Anaconda _Anconda] 9. [Pycharm 提示:this license \*\*\*\* has been cancelled][Pycharm _this license _ has been cancelled] 10. [Pycharm 设置开发模板/字体大小/背景颜色][Pycharm] 未经允许不得转载:[猿说编程][Python 2] » [Python format 函数][format] [Python]: https://www.codersrc.com/python [Python 1]: https://www.codersrc.com/pythonsimple [format]: https://www.codersrc.com/archives/4809.html [Python 2]: https://www.codersrc.com [print]: https://www.codersrc.com/archives/4775.html [5019994a6366d22ae2c56ecc9ab95f40.png]: /images/20221005/ebed1dc7ee864c8f8021ff18cc73a3f4.png [Python 3]: https://www.codersrc.com/archives/4273.html [Python Pycharm Anacanda]: https://www.codersrc.com/archives/4346.html [Python2.x _ Python3.x]: https://www.codersrc.com/archives/4470.html [Python 4]: https://www.codersrc.com/archives/4397.html [Python Hello World]: https://www.codersrc.com/archives/4410.html [Python 5]: https://www.codersrc.com/archives/4724.html [Python 6]: https://www.codersrc.com/archives/4753.html [Anaconda _Anconda]: https://www.codersrc.com/archives/4588.html [Pycharm _this license _ has been cancelled]: https://www.codersrc.com/archives/4708.html [Pycharm]: https://www.codersrc.com/archives/4735.html
还没有评论,来说两句吧...