Python:如何写输入与输出

简介: Python 中如何写输入与输出?

在 Python 中调用 print 时,实际上是调用 sys.stdout.write(obj + '\n')sys.stdin.readline() 会将标准输入全部获取,包括末尾的换行符 \n,因此用 len 计算长度是包含了换行符的,用这种方法输入时可以用 strip() 来去掉换行符(或者用 sys.stdin.readline()[:-1])。

sys.stdin.readline().trip() 就等价于 input()

注意:Python 2 和 Python 3 的输入输出稍微有区别。在使用 Python 2 的时候最好用 sys.stdin 的方式读取,用 input() 对于字符串和数字相混合的输入会报错。

例如对于 S 0 这种数据,Python 2 要求对于字符串需要用引号,如 “S” 0,否则无法识别。

import sys
# strip() 去掉两端的空白符,返回 str
# split() 按照空白符分割,返回 List[str]
# map(type, x) 把列表 x 中的元素映射成类型 type
# 1. 题目没有告知多少组数据时,用 while True
while True:
    try:
        # ...
    except:
        break
        
# 2. 题目告知有 T 组数据时,用 For loop
T = int(input().strip())
for _ in range(T):
    # ...
    
    
# 3. 不同的输入
s = input().strip()  # 输入一个字符
str_ = sys.stdin.readline().strip()  # 读取一行
num = int(input().strip())  # 输入一个整数
nums = list(map(int, input().strip().split()))  # 输入一个整数列表

要是想要写完整一点可以:

import sys

if __name__ == "__main__":
    # 读取一个整数
    n = int(sys.stdin.readline().strip())
    matrix = list()
    # 读取多行保存到一个列表中, 组成一个矩阵
    for _ in range(n):
        line = sys.stdin.readline().strip()
        row = list(map(int, line.split()))
        matrix.append(row)
目录
相关文章
|
20天前
|
Python
python的输入和输出
python的输入和输出
62 2
|
7月前
|
Python
06 python - 输出和输入
06 python - 输出和输入
40 0
|
20天前
|
Python
Python的输入与输出
Python的输入与输出
13 1
|
20天前
|
JSON Java Go
Python输入和输出
Python输入和输出
|
6月前
|
前端开发 Shell 程序员
Python 教程之输入输出(2)—— 输入和输出
Python 教程之输入输出(2)—— 输入和输出
56 0
|
10月前
|
存储 数据安全/隐私保护 Python
【从零学习python 】05. Python中的输出和输入
【从零学习python 】05. Python中的输出和输入
88 0
|
11月前
|
Python
|
11月前
|
Python
|
11月前
|
Python
|
存储 Python
如何用python编程输入与输出?【零基础Python教程005】
如何用python编程输入与输出?【零基础Python教程005】
144 0