2024-06-20

2024-06-19  本文已影响0人  ADolphin

输出函数print用法(Python3):

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

这里是 print 函数的参数说明:


print('jiujiang')
print("kejiangmin",47,True,"江西九江")
print("kejiangmin",47,True,"江西九江",sep='|')
# kejiangmin|47|True|江西九江

# 打开一个文件以写入内容,如果文件不存在则创建它  
with open('output.txt', 'w') as f: 
    # 使用 print 函数将内容写入文件  
    print('Hello, world!', file=f)  
# 此时,'output.txt' 文件将包含 "Hello, world!"

# 刷新输出流(通常在需要立即看到输出时使用,例如在网络编程中)  
print("Hello, flush!", flush=True)

请注意,在大多数情况下,你不需要指定 file 和 flush 参数,除非你打算将输出重定向到文件或需要立即刷新输出流。在大多数情况下,只使用 print 函数的基本形式就足够了。


格式占位符的三种用法

使用%操作符,你可以定义占位符来插入变量。占位符由%后跟类型说明符组成(如%s用于字符串,%d用于整数,%f用于浮点数等)。

print("姓名:%s,年龄:%d,居住地:%s,卡余额:%.2f。"%("kejiangmin",47,"江西九江",3478.5))
# 姓名:kejiangmin,年龄:47,居住地:江西九江,卡余额:3478.50。

str.format() 是 Python 中字符串格式化的一个强大方法。它允许你使用占位符(例如 {})在你的字符串中,并通过 .format() 方法提供值来替换这些占位符。这种方法提供了比旧的 % 格式化方法更多的灵活性和功能。

{}中的格式说明:

"{:[[fill]align][sign][#][0][minimumwidth][group][.precision][type]}".format()
[[填充]对齐方式 ][正负号][#][0][宽度][分组选项][精度][类型]

填充和对齐方式:
使用<(左对齐)、>(右对齐)、^(居中对齐)以及一个可选的填充字符(默认为空格)来控制,使用填充必须用对齐方式。
正负号:
使用+表示始终显示正负号,-(或默认)表示仅在负数时显示负号。
#
对于整数类型,#常用于指定进制前缀(如二进制0b、八进制0o或十六进制0x)。对于浮点数,它可能用于显示特殊格式(如inf、nan)。
0
在整数和浮点数格式化中,0用作填充字符,并通常与宽度一起使用,以确保数值具有指定的总宽度,并且在需要时使用零填充。
宽度:
指定字段的最小宽度。如果值比此宽度短,则使用填充字符进行填充。
分组选项:
添加千位分隔符,或连线符_。
精度:
对于浮点数,.后面跟的数字指定小数点后的位数。对于字符串,它可能表示最大字段宽度。
类型:
指定要使用的格式类型,如f(浮点数)、s(字符串)、d(整数)等。

# 填充和对齐方式  
print('{:0>10}'.format(123))  # 使用0填充到总宽度10,右对齐: '0000000123'  
print('{:<10}'.format(123))   # 使用空格填充到总宽度10,左对齐: '123       '  
print('{:^10}'.format(123))   # 使用空格填充到总宽度10,居中对齐: '   123    '  
  
# 正负号  
print('{:+d}'.format(123))    # 显示正号: '+123'  
print('{:-d}'.format(-123))   # 显示负号(默认): '-123'  
  
# # 前缀  
print('{:#010x}'.format(255)) # 十六进制,显示0x前缀并用0填充: '0x000000ff'  
  
# 0 填充和宽度  
print('{:010d}'.format(123))  # 使用0填充到总宽度10: '0000000123'  
  
# 精度  
print('{:.2f}'.format(123.4567))  # 浮点数,保留两位小数: '123.46'  
  
# 字符串类型(这里显式指定,但通常不需要)  
print('{:s}'.format('hello'))     # 字符串: 'hello'  
print('{:d}'.format(123))         # 整数: '123'  
  
# 分组选项(自定义实现)  
number = 123456789  
formatted = '{:,}'.format(number)  # 使用逗号作为千位分隔符: '123,456,789'  
# 注意:这不是`str.format()`的内置选项,而是利用了内置的逗号分隔符格式化

知识检查

  1. [#][0]用于二、八、十六进制中,前者是补前缀,后者是是在前缀后数值前补0
  2. [精度]用于字符串时,如果实际长度比设置宽度大,有截断字符串的作用。
print("{:.2s}".format("aaaaa")  # aa
  1. [分组选项]只适合数值,可选择逗号,和下划线 _
 "{:10,.2f}".format(122222.3456)   # 122,222.35
  1. [类型] d和s这两种类型经常可以省略

进一步练习

  1. 格式化数字
    精度格式化:
    保留指定位数的小数:"{:.2f}".format(3.1415926) #输出 3.14
    整数千位分隔符: "{:,}".format(1234567) #输出 1,234,567
    进制转换:
    二进制:"{:b}".format(10) #输出 1010
    八进制:"{:o}".format(10) #输出 12
    十六进制(小写):"{:x}".format(255) #输出 ff
    十六进制(大写):"{:X}".format(255) #输出 FF
  2. 格式化字符串
    对齐和填充:
    左对齐:"{:<10}".format("foo") #输出 foo
    居中对齐:"{:^10}".format("bar") #输出 bar
    右对齐:"{:>10}".format("baz") #输出 baz
    自定义填充字符(如使用*填充):"{:*>10}".format("bar") #输出 *****bar***
    字符串截取:
    截取前三个字符:"{:.3}".format("helloworld") #输出 hel
  3. 格式化日期和时间
    使用 datetime 模块:
    日期格式化:"{:%Y-%m-%d}".format(datetime.date(2023, 3, 15)) #输出 2023-03-15
    时间格式化:"{:%H:%M:%S}".format(datetime.time(12, 34, 56)) #输出 12:34:56
    日期时间格式化:"{:%Y-%m-%d %H:%M:%S}".format(datetime.datetime(2023, 3, 15, 12, 34, 56)) #输出 2023-03-15 12:34:56
  4. 格式化对象和属性
    访问对象的属性:
    假设有一个 Person 类,可以使用{0.name} 或 {name}访问其 name 属性。
  5. 格式化字典
    使用 ** 解包字典作为关键字参数:
    "{name} is {age} years old".format(**{"name": "Alice", "age": 30}) #输出 Alice is 30 years old
  6. 嵌套和转义
    嵌套 .format():
    "{{0}} {}".format("foo", "bar") #输出 {0} bar
    转义大括号:
    在字符串中表示大括号 { 或 },使用 {{ 或 }} 来转义。
  7. 格式化列表和元组
    虽然 .format() 不直接支持列表和元组的格式化,但可以通过循环、列表推导式或 *args 来实现。

知识拓展

Finally, the ‘type’ determines how the data should be presented.
The available integer presentation types are:
'b' - Binary. Outputs the number in base 2.
'c' - Character. Converts the integer to the corresponding
Unicode character before printing.
'd' - Decimal Integer. Outputs the number in base 10.
'o' - Octal format. Outputs the number in base 8.
'x' - Hex format. Outputs the number in base 16, using
lower-case letters for the digits above 9.
'X' - Hex format. Outputs the number in base 16, using
upper-case letters for the digits above 9.
'n' - Number. This is the same as 'd', except that it uses the
current locale setting to insert the appropriate
number separator characters.
'' (None) - the same as 'd'


The available floating point presentation types are:
'e' - Exponent notation. Prints the number in scientific
notation using the letter 'e' to indicate the exponent.
'E' - Exponent notation. Same as 'e' except it converts the
number to uppercase.
'f' - Fixed point. Displays the number as a fixed-point
number.
'F' - Fixed point. Same as 'f' except it converts the number
to uppercase.
'g' - General format. This prints the number as a fixed-point
number, unless the number is too large, in which case
it switches to 'e' exponent notation.
'G' - General format. Same as 'g' except switches to 'E'
if the number gets to large.
'n' - Number. This is the same as 'g', except that it uses the
current locale setting to insert the appropriate
number separator characters.
'%' - Percentage. Multiplies the number by 100 and displays
in fixed ('f') format, followed by a percent sign.
'' (None) - similar to 'g', except that it prints at least one
digit after the decimal point.
Objects are able to define their own format specifiers to replace the standard ones. An example is the ‘datetime’ class, whose format specifiers might look something like the arguments to the strftime() function:
"Today is: {0:%a %b %d %H:%M:%S %Y}".format(datetime.now())
For all built-in types, an empty format specification will produce the equivalent of str(value). It is recommended that objects defining their own format specifiers follow this convention as well.


f-string(格式化字符串字面值)是Python 3.6及以上版本中引入的一种简洁的字符串格式化方法。你可以在字符串前加上f或F,并在字符串内部使用大括号{}来包含表达式。这些表达式将在运行时被求值,并转换为字符串。

name = "kejiangmin"  
age = 47
print(f"My name is {name} and I am {age} years old.")
number = 123456789  
width = 10  
precision = 2  
  
# 填充和对齐方式(f-string中通常不直接支持,但可以结合表达式)  
formatted = f'{"{number:0>{width}}"}'  # 使用0填充到总宽度10: '000000123456789'  
  
# 正负号(f-string直接支持)  
formatted = f'{+number}'  # 显示正号(但通常对正数来说是多余的)  
  
# 精度(f-string直接支持)  
formatted = f'{number:.{precision}f}'  # 浮点数,保留两位小数(假设number是浮点数): '12
上一篇 下一篇

猜你喜欢

热点阅读