python之格式化输出format()函数使用总结
创始人
2024-12-26 18:36:18
0

        在 Python 中,format 方法是一种用于字符串格式化的强大工具。它允许你将变量或表达式插入到字符串中,并根据需要进行格式化。下面是对 format 方法的详细介绍:

        format 方法的基本语法如下:

formatted_string = "string {0} {1}".format(arg1, arg2)

       在这个语法中,被大括号 {} 包围的占位符用于指示将要插入的变量的位置。format 方法的参数将按照位置顺序填充到占位符中。

下面是 format 方法的一些常见用法和格式选项:

1. 位置参数

        可以使用位置参数将变量插入到字符串中。

name = "John" age = 30 message = "My name is {}, and I'm {} years old.".format(name, age) message = "My name is {0}, and I'm {1} years old.".format(name, age) print(message)

        输出:"My name is John, and I'm 30 years old."。

2. 关键字参数

        除了位置参数外,还可以使用关键字参数指定要插入的变量。

name = "John" age = 30 message = "My name is {name}, and I'm {age} years old.".format(name=name, age=age) print(message)

        输出:"My name is John, and I'm 30 years old."。

3. 格式选项

        可以在占位符中使用格式选项来控制变量的显示方式。

number = 12345.6789 formatted_number = "Formatted number: {:.2f}".format(number) print(formatted_number)

       输出:"Formatted number: 12345.68"。在这个例子中,:.2f 表示将浮点数格式化为保留两位小数的形式。

4. 对齐和填充

        可以使用格式选项来控制字符串的对齐和填充方式。

name = "John" formatted_name = "Name: {:>10}".format(name) print(formatted_name)

        输出:"Name: John"。在这个例子中,{:>10} 表示将字符串右对齐,并在左侧填充空格,总宽度为 10。

5. 格式化类型

        format 方法支持不同的格式化类型,例如整数、浮点数、十六进制等。

number = 42 formatted_number = "Formatted number: {:b}".format(number) print(formatted_number)

        输出:"Formatted number: 101010"。在这个例子中,{:b} 表示将整数格式化为二进制形式。

        上述示例,是 format 方法的一些常见用法和格式选项。可以根据需要使用不同的格式化选项和参数,根据具体的需求来定制输出字符串的格式

附测试代码:

name  = "Jone" age = 30  #位置参数 print("My name is {}, and I am {} years old!".format(name, age)) #{}中不指定索引,默认第一个位置为0,第二个位置为1 print("My name is {1}, and I am {0} years old!".format(age, name)) #{}中指定索引,按照参数中索引进行取值  #关键字参数 print("My name is {Name}, and I am {Age} years old!".format(Name=name, Age=age))  #格式化选项 number = 1234.5678 print("Number is {:.2f}".format(number)) #输出2位小数  #对齐和填充 print("Name:{:>10}".format(name)) #总共占十位,右对齐  #格式化数据类型 number = 42 print("Format number is {:b}".format(number)) #输出2进制

输出结果:

相关内容

热门资讯

透视规律"wepok... 透视规律"wepoker私人局俱乐部"原来真的是有挂(透视)爆料教程(有挂介绍);1、在wepoke...
透视辅助!aapoker如何设... 透视辅助!aapoker如何设置胜率(透视)透视脚本(原来是真的有挂)1、任何aapoker如何设置...
透视美元局!pokerworl... 透视美元局!pokerworld破解版下载,本来是真的有挂(透视)AI教程(有挂技巧)1、poker...
透视能赢"hhpok... 透视能赢"hhpoker哪个俱乐部靠谱"确实有挂(透视)玩家教你(有挂方法)1、操作简单,无需注册,...
透视好友!aapoker透视脚... 透视好友!aapoker透视脚本下载(透视)万能辅助器(都是是真的有挂)1、任何aapoker透视脚...
透视游戏!wepoker辅助工... 透视游戏!wepoker辅助工具,其实存在有挂(透视)教你攻略(有挂揭秘);1、wepoker辅助工...
透视辅助"pokem... 透视辅助"pokemmo手机脚本"果然真的有挂(透视)2025版教程(有挂脚本)1、每一步都需要思考...
透视有挂!aapoker怎么设... 透视有挂!aapoker怎么设置提高好牌几率(透视)透视脚本下载(一直真的是有挂)1)aapoker...
透视数据!wepoker免费脚... 透视数据!wepoker免费脚本,确实有挂(透视)分享教程(有挂详情)一、wepoker免费脚本AI...
透视苹果版"hhpo... 透视苹果版"hhpoker智能辅助插件"原来是有挂(透视)玩家教你(有挂脚本);1、上手简单,内置详...