python格式化输出方法。

本文介绍了Python中字符串格式化的format方法及其使用技巧,并详细解释了如何利用format方法进行参数显示格式控制。此外,还讲解了print函数的高级用法,如sep, end和file参数的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.format()方法。

字符串类型格式化采用format()方法,基本使用格式是:

     <模板字符串>.format(<逗号分隔的参数>)

调用format()方法后会返回一个新的字符串,参数从0 开始编号。

a = int(input())
b = int(input())

print('{0} \n{1} \n{2}'.format((a + b), (a - b), (a * b)))

format()方法中<模板字符串>的槽除了包括参数序号,还可以包括格式控制信息。此时,槽的内部样式如下:

     {<参数序号>: <格式控制标记>}

     其中,<格式控制标记>用来控制参数显示时的格式,包括:<填充><对齐><宽度>,<.精度><类型>6 个字段,这些字段都是可选的,可以组合使用,逐一介绍如下。

s = "PYTHON"
 
"{0:30}".format(s)
Out[17]: 'PYTHON                        '
 
"{0:>30}".format(s)
Out[18]: '                        PYTHON'
 
"{0:*^30}".format(s)
Out[19]: '************PYTHON************'

②:sep,end,file的用法。

 with open('abc.txt','w') as f:
 print("file\n","abc","fff",sep='#########\n',end='',file=f)
其结果:
将输出写到了文件abc.txt。
abc.txt的内容如下:
file
#########
abc
#########
fff
### Python 格式化输出方法 Python 提供了三种主要的格式化输出方法:% 格式化、`str.format()` 方法以及 `f-string`(格式化字符串字面量)。以下是每种方法的具体说明及其示例。 #### 1. `% 格式化` 这是最早的一种格式化方法,类似于 C 语言中的 `printf` 函数。通过使用 `%` 符号作为占位符,并将其与对应的值匹配完成格式化操作[^1]。 ```python name = "Alice" age = 30 formatted_str = "My name is %s and I am %d years old." % (name, age) print(formatted_str) ``` 此代码会输出: `My name is Alice and I am 30 years old.` --- #### 2. `str.format()` 方法Python 2.7 起引入的 `str.format()` 方法提供了一种更加灵活的方式来进行字符串格式化。它允许开发者在字符串中定义 `{}` 占位符并传入相应参数[^2]。 基本语法如下: ```python name = "Alice" age = 30 formatted_str = "My name is {} and I am {} years old.".format(name, age) print(formatted_str) ``` 同样会输出: `My name is Alice and I am 30 years old.` 还可以指定索引位置或命名参数以增强可读性和灵活性: ```python formatted_str_with_index = "{1} is {0} years old.".format(age, name) print(formatted_str_with_index) formatted_str_named_params = "Name: {person_name}, Age: {person_age}".format(person_name=name, person_age=age) print(formatted_str_named_params) ``` 这将分别打印: `Alice is 30 years old.` `Name: Alice, Age: 30` --- #### 3. `f-string`(格式化字符串字面量) 从 Python 3.6 开始支持的 `f-string` 是一种简洁高效的字符串格式化方式。只需在字符串前加字母 `f` 或 `F` 并用大括号 `{}` 表达变量即可实现动态嵌套表达式的计算和展示[^4]。 示例如下: ```python name = "Alice" age = 30 formatted_f_string = f"My name is {name} and I am {age} years old." print(formatted_f_string) ``` 运行结果为: `My name is Alice and I am 30 years old.` 此外,`f-string` 支持复杂的表达式求值: ```python a = 5 b = 10 result = f"The sum of {a} and {b} is {a + b}." print(result) ``` 最终输出: `The sum of 5 and 10 is 15.` --- ### 总结 以上介绍了 Python 的三种常见格式化输出方法:`%` 格式化、`str.format()` 和 `f-string`。尽管它们都能满足大多数场景下的需求,但在实际开发过程中推荐优先考虑 `f-string`,因其具有更高的性能表现和更好的可维护性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值