#26865: [Python]可以改變stdin的讀取方式


406490150@gms.tku.edu.tw (我是朱朱)

學校 : 國立交通大學
編號 : 139794
來源 : [140.113.236.122]
最後登入時間 :
2022-09-03 11:13:16
e972. 1. 貨幣轉換 (Currency) -- 2019年5月TOI練習賽新手組 | From: [1.172.253.7] | 發表日期 : 2021-08-29 00:10

因為第三筆測資 以 \r 作為換行,可以將stdin重新導向,就可以正常使用了

 

from sys import stdin

stdin = open(0, newline=None)

或是

import io

from sys import stdin

stdin = io.TextIOWrapper(stdin.buffer)

兩種方法都可以

 

如果Python版本在3.7以上的話,可以用以下方式更改,可惜 ZJ 是3.6版,所以這個方法不適用這題

sys.stdin.reconfigure(newline=None)

 

參考資料:

https://stackoverflow.com/questions/50476200/changing-the-way-stdin-stdout-is-opened-in-python-3

 

 

In [16]: stdin?

Type:        TextIOWrapper

String form: <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>  

Docstring:

Character and line based layer over a BufferedIOBase object, buffer.       

 

encoding gives the name of the encoding that the stream will be

decoded or encoded with. It defaults to locale.getpreferredencoding(False).

errors determines the strictness of encoding and decoding (see

help(codecs.Codec) or the documentation for codecs.register) and

defaults to "strict".

 

newline controls how line endings are handled. It can be None, '',

'\n', '\r', and '\r\n'.  It works as follows:

 

* On input, if newline is None, universal newlines mode is

  enabled. Lines in the input can end in '\n', '\r', or '\r\n', and   

  these are translated into '\n' before being returned to the

  caller. If it is '', universal newline mode is enabled, but line    

  endings are returned to the caller untranslated. If it has any of   

  the other legal values, input lines are only terminated by the given

  string, and the line ending is returned to the caller untranslated. 

 

* On output, if newline is None, any '\n' characters written are      

  translated to the system default line separator, os.linesep. If     

  newline is '' or '\n', no translation takes place. If newline is any

  of the other legal values, any '\n' characters written are translated    

  to the given string.

 

If line_buffering is True, a call to flush is implied when a call to       

 

write contains a newline character.

 
ZeroJudge Forum