python---输入输出

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 格式化输出字符串是指将变量或常量按照一定的格式输出到屏幕或文件中。在Python中,可以使用字符串格式化操作符“%”或字符串的format()方法来实现。 例如,假设有一个变量x=3.1415926,我们想要将它输出为保留两位小数的浮点数,可以使用以下代码: print("x的值为:%.2f" % x) 或者使用format()方法: print("x的值为:{:.2f}".format(x)) 输出结果为: x的值为:3.14 其中,“%.2f”表示输出浮点数,保留两位小数,“{:.2f}”表示输出浮点数,保留两位小数。 除了浮点数,还可以格式化输出整数、字符串、布尔值等类型的变量或常量。具体的格式化方式可以参考Python官方文档。 ### 回答2: Python作为一种高级编程语言,非常适合处理各种数据类型和格式,其输入输出功能也非常强大。在Python输入输出中,格式化输出字符串是一项非常关键的操作。 格式化输出字符串是指Python将数据按照特定的格式输出到终端上或者写入文件中。Python提供了多种格式化输出字符串的方式,其中最常用的方式是使用字符串格式化操作符“%”。 使用“%”操作符时,需要在字符串中使用特殊字符“%”来表示被替换的位置,然后在字符串后面使用一个元组或字典来传递需要输出的值。例如: ``` name = 'Tom' age = 25 print('My name is %s, and I am %d years old.' % (name, age)) ``` 上述代码中,“%s”和“%d”分别表示需要输出的字符串和数字类型。相应的值用元组(name, age)表示,分别对应字符串变量name和整数变量age。当然,可以使用多个“%”操作符来实现多个变量的输出,例如: ``` hour = 9 minute = 30 second = 45 print("%02d:%02d:%02d" %(hour, minute, second)) ``` 在Python中,还有其他可以实现字符串格式化输出的方法,比如使用format方法,使用f字符串(Python 3.6及以上版本)。这些方法各有特点,但是字符串格式化操作符“%”是最常用的一种方式,可以在很多场景下发挥重要作用。 总之,在Python输入输出中,格式化输出字符串是非常重要的一项操作,可以帮助我们更好地输出各种类型的数据,提高程序的可读性和可维护性。对于Python开发者来说,熟练掌握字符串格式化输出的各种方法是非常必要的。 ### 回答3: Python中的格式化输出字符串是指将不同类型的数据按照特定的格式输出成字符串。在实际的编程过程中,格式化输出字符串的作用非常重要,可以很好的提高程序的可读性和易用性。 在Python中,格式化输出字符串有两种方式:一种是使用字符串格式化运算符(%),另一种是使用字符串的format方法。 使用字符串格式化运算符(%)的方式,基本语法如下: ``` %s: 字符串类型 %d: 整数类型 %f: 浮点数类型 %x: 十六进制整数类型 %%: 输出% ``` 例如,我们要将字符串和整数类型的数据格式化为字符串输出: ``` name = 'Alice' age = 18 print('My name is %s, I am %d years old.' % (name, age)) ``` 使用字符串的format方法,基本语法如下: ``` {数字格式或关键字格式} ``` 例如,我们要将字符串和整数类型的数据格式化为字符串输出: ``` name = 'Alice' age = 18 print('My name is {}, I am {} years old.'.format(name, age)) ``` 除了以上两种方式,Python中还提供了一种更加强大的格式化字符串方式——f-string,也称为格式化字符串字面量(Formatted string literals)。它的语法比较简单,可以直接在字符串前加上f,然后在字符串中使用{表达式}来嵌入变量值。 例如: ``` name = 'Alice' age = 18 print(f'My name is {name}, I am {age} years old.') ``` 总之,格式化输出字符串的方式有多种,开发者可以根据实际需求自由选择使用。在实际开发中,应该根据数据类型和输出的场景选择适合的方式,以保证输出的字符串具有良好的可读性和易用性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值