python---输入输出

本文介绍Python中格式化字符串的方法,包括基本语法、位置参数、名称参数等,并演示如何使用花括号{}

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

Format String Syntax

格式化字符串包含用花括号 {} 括起来的“可替代字段”。 花括号中不包含的所有内容均视为文字文本,该文本保持原样输出。 如果需要在文字文本中包含花括号字符,可以通过使用 {{}} 来转义。

可替代字段的语法如下:

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | digit+]
attribute_name    ::=  identifier
element_index     ::=  digit+ | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  <described in the next section>
format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

在大多数情况下,语法类似于旧的 % 格式,只是添加了 {} ,使用 : 而不是 %。 例如,可以将 '%03.2f' 转换为 '{:03.2f}'

>>> print('{:o}'.format(20))
24
>>> print('{0:o}'.format(20))
24
>>> print('%o' % 20)
24

通过位置访问参数:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')

'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')

'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')
'abracadabra'
>>> 

通过名字访问参数:

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

访问参数的属性

>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
 'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
	def __init__(self, x, y):
		self.x, self.y = x, y
	def __str__(self):
		return 'Point({self.x}, {self.y})'.format(self=self)

	
>>> str(Point(4,2))
'Point(4, 2)'

关键字参数

# print() 函数有可选的变元 end 和 sep,分别指定在参数末尾打印什么,以及在参数之间打印什么来隔开它们。

# 这两个字符串出现在独立的两行中,因为 print() 函数自动在传入的字符串末尾添加了换行符
print("Hello")
print("World")

# 可以设置 end 关键字参数,指定在末尾打印什么
print("Hello", end=' ')
print("World")

# 如果向 print() 传入多个字符串值,该函数就会自动用一个空格分隔他们
print('cats', 'dogs', 'mice')

# 可以设置 sep 关键字参数,替换掉默认的字符分隔符
print('cats', 'dogs', 'mice', sep=',')
Hello
World
Hello World
cats dogs mice
cats,dogs,mice

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值