写程序的目的就是要与外界进行交互,通过输入输出来完成一定操作,从而解决一定的问题。因此,输入、输出的处理便是需要程序员掌握的一个重点内容。本文主要记录输入输出的相关函数以及常见编程方式。

输出

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
2
3
4
5
6
In [20]: print("hello","world")
hello world

In [23]: sys.stdout.write("hello"+" "+"world"+"\n")
hello world
Out[23]: 12

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
2
In [31]: print("hello", "world", sep="--")
hello--world

end

控制打印的结尾,默认是: end='\n' , 即: print 默认输出换行。 如果想要不换行, 显式修改 end 参数: end=""

如果想打印以空格结尾,可以使用下面代码:

1
print(obj1,obj2, end=' ')

end 默认是 '' , 所以会输出空格

file

file 用来改变 print 输出流,默认输出到 sys.stdout 。 它可以发挥两个重要作用:

  1. 输出到 stderr (注:了解 stderr, 看文末扩展)

    这个功能, 日常小脚本用不到,但是做一些大点的项目的时候,还有有用的。

  2. 输出到外部文件,和 fp 指针的 write 功能相似,但是注意:写二进制文件时,不能用它,需要使用文件的 write 方法。

1
2
In [8]: print("Hello World", file=sys.stderr)
Hello World
1
2
3
4
5
6
In [13]: with open("sample", "a", encoding="utf8") as fp:
...: print("Hello World", file=fp)
...:

In [14]: cat sample
Hello World

flush

flush -- 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新。 使用 flush 参数生成一个 Loading 的效果:

1
2
3
4
5
6
7
8
import time

print("---RUNOOB EXAMPLE : Loading 效果---")

print("Loading",end = "")
for i in range(20):
print(".",end = '',flush = True)
time.sleep(0.5)

参考自:Python print() 函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
In [1]: print("-"*25)
----------------------mathjax: true
---```

### 垂直对齐

使用制表符 `\t` 在垂直方向对齐。

```python
In [8]: def main():
...: print("1\t2\t3")
...: print("12\t13\t14")
...:

In [9]: main()
1 2 3
12 13 14

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
2
3
4
In [17]: hug = "hello"
In [18]: year = 2020
In [20]: f"{hug} {year}"
Out[20]: 'hello 2020'

初学者往往误将字符串和其他类型,如:字符串,异常类型进行拼接,从而得到一下错误: TypeError: can only concatenate str (not "int") to str , 这是由于 Python

arbitrary expression

由于 f 字符串是在运行时进行计算的,因此可将任何有效的 Python 表达式放入其中。

arithmetic

1
2
In [29]: f"{2020//521} You Me & Her {2*5//10}"
Out[29]: '3 You Me & Her 1'

function

1
2
3
4
def double_value(value):
return value*value
num = 4
print(f"{double_value(num)}")

method

You also have the option of calling a method directly:

1
2
3
4
5
In [38]: test
Out[38]: 'www.google.com'

In [39]: f"{test.upper()}"
Out[39]: 'WWW.GOOGLE.COM'

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
2
3
4
5
6
7
8
9
10
>>> name = "Eric"
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> message = (
... f"Hi {name}. "
... f"You are a {profession}. "
... f"You were in {affiliation}."
... )
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'

If you want to spread strings over multiple lines, you also have the option of escaping a return with a \ :

1
2
3
4
5
6
7
>>> message = f"Hi {name}. " \
... f"You are a {profession}. " \
... f"You were in {affiliation}."
...
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'

But this is what will happen if you use """ :

1
2
3
4
5
6
7
8
>>> message = f"""
... Hi {name}.
... You are a {profession}.
... You were in {affiliation}.
... """
...
>>> message
'\n Hi Eric.\n You are a comedian.\n You were in Monty Python.\n'

多行字符串会包含跨行每行开头的缩进

Dictionaries

如果 f-string 中需要使用和外围一样的引号(单双引号)时,可以使用 \ 转义。

1
2
3
>>> comedian = {'name': 'Eric Idle', 'age': 74}
>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."
The comedian is Eric Idle, aged 74.

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
2
3
>>> f"{{74}}"
'{74}'

Note that using triple braces will result in there being only single braces in your string:

1
2
3
>>> f"{{{74}}}"
'{74}'

However, you can get more braces to show if you use more than triple braces:

1
2
>>> f"{{{{74}}}}"
'{{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
2
3
newline = ord('\n')

f"newline: {newline}"

Inline Comments

Expressions should not include comments using the ## symbol. You’ll get a syntax error:

1
2
3
4
5
6
7
8
>>> f"Eric is {2 * 37 ##Oh my!}."

File "<stdin>", line 1
f"Eric is {2 * 37 ##Oh my!}."

^
SyntaxError: f-string expression part cannot include '##'

进制

题目: string-formatting

1
2
3
4
5
6
7
8
def print_formatted(number):
width = len(f"{number:b}")
for i in range(1, number+1):
print(f"{i:{width}d} {i:{width}o} {i:{width}X} {i:{width}b}")

if __name__ == '__main__':
n = int(input())
print_formatted(n)

输入

  1. Problem 1:

    finding-the-percentage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
```

1. 已知读入的数据的个数,可以使用 for 循环读取,使用 `_` (一般指不需要用到的变量)作为每次迭代的结果变量。
2. 使用 `input().split()` 将读入的一行以空格(或制表符)分隔的字符串( `input()` 遇到回车结束)分裂为字符(串) 列表。
3. 在函数名前加 `*` , 标识可以接受多值作为元组

2. Problem 2:

[处理输入 案例2](https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem):

``` python
num = int(input())

score = [int(n) for n in input().split()][:num]
```

或者

``` python
num = int(input())
score =list(map(int,input().split()))[:num]
```

3. Problem 3:

[python3——读取以空格分隔的一行整数](https://blog.csdn.net/u013595395/article/details/88425996)

4. Problem 4

[Symmetric Difference](https://www.hackerrank.com/challenges/symmetric-difference/forum)

将以下输入的第二行和第四行分别转换为字典

```txt
4
2 4 5 9
4
2 4 11 12

方法: a,b = [set(input().split()) for _ in range(4)][1::2]

首先使用 for 循环读取到列表,然后取列表的第 2,4 项

输出案例

  1. 将多个数字列表空格分隔输出,结尾无空格,不同列表用换行分隔
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!