Python input/output
写程序的目的就是要与外界进行交互,通过输入输出来完成一定操作,从而解决一定的问题。因此,输入、输出的处理便是需要程序员掌握的一个重点内容。本文主要记录输入输出的相关函数以及常见编程方式。
输出
print 作为 python 中最常用输出函数,功能比较强大,所以单独记录,并练习一下。
原理
当我们使用 print(obj1, obj2)
在 console
上打印对象的时候,实质上调用的是
sys.stdout.write(obj1+" "+obj2+'\n')
Will be converted to string before printed
print
可以输出任意对象,但是需要先将其转换为字符串的原因是:
sys.stdout.write
只能输出字符串。
sys.stdout.write
1 | In [20]: print("hello","world") |
Syntax
print(object(s), sep=separator, end=end, file=file, flush=flush)
== sys.stdout.write(str(object(s))+"\n")
Parameter Values
object(s) | Any object, and as many as you like. Will be converted to string before printed |
---|---|
sep='separator' | Optional. Specify how to separate the objects, if there is more than one. Default is ' ' |
end='end' | Optional. Specify what to print at the end. Default is '\n' (line feed) |
file | Optional. An object with a write method. Default is sys.stdout |
flush | Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False |
记录一下不熟悉且重要的参数的使用。
separator
当 print
输出多个对象时, 默认是以空格分割,即:
sep=" "
, 如果想要修改,显式地添加该参数即可。
1 | In [31]: print("hello", "world", sep="--") |
end
控制打印的结尾,默认是: end='\n'
, 即:
print
默认输出换行。 如果想要不换行, 显式修改 end 参数:
end=""
如果想打印以空格结尾,可以使用下面代码:
1 | print(obj1,obj2, end=' ') |
end 默认是 '' , 所以会输出空格
file
file 用来改变 print 输出流,默认输出到 sys.stdout
。
它可以发挥两个重要作用:
输出到
stderr
(注:了解 stderr, 看文末扩展)这个功能, 日常小脚本用不到,但是做一些大点的项目的时候,还有有用的。
输出到外部文件,和 fp 指针的 write 功能相似,但是注意:写二进制文件时,不能用它,需要使用文件的 write 方法。
1 | In [8]: print("Hello World", file=sys.stderr) |
1 | In [13]: with open("sample", "a", encoding="utf8") as fp: |
flush
flush -- 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。 使用 flush 参数生成一个 Loading 的效果:
1 | import time |
print 重复打印
1 | In [1]: print("-"*25) |
f-string 格式化输出
The idea behind f-strings is to make string interpolation simpler. F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.
Note : F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format().
Simple Syntax
f-string 的使用几乎和 str.format()
使用方式几乎类似,
当然, 使用大写 F
也可。
1 | In [17]: hug = "hello" |
初学者往往误将字符串和其他类型,如:字符串,异常类型进行拼接,从而得到一下错误:
TypeError: can only concatenate str (not "int") to str
,
这是由于 Python
arbitrary expression
由于 f 字符串是在运行时进行计算的,因此可将任何有效的 Python 表达式放入其中。
arithmetic
1 | In [29]: f"{2020//521} You Me & Her {2*5//10}" |
function
1 | def double_value(value): |
method
You also have the option of calling a method directly:
1 | In [38]: test |
user-defined class
You could even use objects created from classes with f-strings. Imagine you had the following class: -- 见文末的原文(链接),类还没好好学,先不看它。
Multiline f-Strings
Remember that you need to place an f in front of each line of a multiline string.
1 | "Eric" name = |
If you want to spread strings over multiple lines, you also have the
option of escaping a return with a \
:
1 | >>> message = f"Hi {name}. " \ |
But this is what will happen if you use """
:
1 | f""" message = |
多行字符串会包含跨行每行开头的缩进
Dictionaries
如果 f-string 中需要使用和外围一样的引号(单双引号)时,可以使用
\
转义。
1 | 'name': 'Eric Idle', 'age': 74} comedian = { |
If you use the same type of quotation mark around the dictionary keys as you do on the outside of the f-string, then the quotation mark at the beginning of the first dictionary key will be interpreted as the end of the string.
Braces
In order to make a brace appear in your string, you must use double braces:
1 | f"{{74}}" |
Note that using triple braces will result in there being only single braces in your string:
1 | f"{{{74}}}" |
However, you can get more braces to show if you use more than triple braces:
1 | f"{{{{74}}}}" |
Backslashes
As you saw earlier, it is possible for you to use backslash escapes in the string portion of an f-string. However, you can’t use backslashes to escape in the expression part of an f-string:
Note: Backslash Cannot be used in format string directly.(
\
不能直接用在 {} 里面)
f"newline: {ord('\n')}"
这样会报错 But the documentation
points out that we can put the backslash into a variable as a workaround
though :
1 | newline = ord('\n') |
Inline Comments
Expressions should not include comments using the ##
symbol. You’ll get a syntax error:
1 | f"Eric is {2 * 37 ##Oh my!}." |
进制
1 | def print_formatted(number): |
输入
Problem 1:
1 | if __name__ == '__main__': |
方法:
a,b = [set(input().split()) for _ in range(4)][1::2]
首先使用 for 循环读取到列表,然后取列表的第 2,4 项
输出案例
- 将多个数字列表空格分隔输出,结尾无空格,不同列表用换行分隔
1 | print(" ".join(str(i) for i in xlist)) |
参考推荐
f-strings in Python 3 – Formatted string literal Python 格式化字符串 f-string 概览 PyFormat Using % and .format() for great good!