Python format 函数- Python零基础入门教程

目录

零基础 Python 学习路线推荐 : Python 学习目录 >> Python 基础入门

一.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 中 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 函数的使用区别!!

注意:format 函数中的下标默认从 0 开始,对顺序没有限制。

三.猜你喜欢

  1. Python 简介
  2. Python Pycharm Anacanda 区别
  3. Python2.x 和 Python3.x,如何选择?
  4. Python 配置环境
  5. Python Hello World 入门
  6. Python 代码注释
  7. Python 中文编码
  8. Anaconda 是什么?Anconda 下载安装教程
  9. Pycharm 提示:this license **** has been cancelled
  10. Pycharm 设置开发模板/字体大小/背景颜色

未经允许不得转载:猿说编程 » Python format 函数

本文由博客 - 猿说编程 猿说编程 发布!

posted @ 2021-07-06 09:44  猿说编程  阅读(1762)  评论(0编辑  收藏  举报