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)
目录
相关文章
|
5月前
|
Python
python的输入和输出
python的输入和输出
78 2
|
11月前
|
Python
06 python - 输出和输入
06 python - 输出和输入
49 0
|
2月前
|
Python
Python笔记7 输入与输出
本文是作者的Python复习笔记第七篇,主要介绍了Python中的输入与输出操作。文中详细解释了如何使用input()函数进行用户输入,包括添加多行字符串提示和字符串转列表输入的方法,以及如何使用print()函数进行格式化输出,提供了多种格式化字符串的示例。
28 0
|
4月前
|
JSON JavaScript 前端开发
Python零基础入门-7 输入与输出
Python零基础入门-7 输入与输出
|
5月前
|
Python
Python的输入与输出
Python的输入与输出
|
5月前
|
JSON Java Go
Python输入和输出
Python输入和输出
|
10月前
|
前端开发 Shell 程序员
Python 教程之输入输出(2)—— 输入和输出
Python 教程之输入输出(2)—— 输入和输出
71 0
|
10月前
|
存储 前端开发 Python
Python 教程之输入输出(1)—— 在 Python 中接受输入
Python 教程之输入输出(1)—— 在 Python 中接受输入
84 0
|
程序员 Python
Python零基础入门(三)——基本输入与输出
Python零基础入门(三)——基本输入与输出
|
存储 Python
如何用python编程输入与输出?【零基础Python教程005】
如何用python编程输入与输出?【零基础Python教程005】
162 0
下一篇
无影云桌面