python中的三種輸入方式


python中的三種輸入方式

python2.X

python2.x中以下三個函數都支持:

raw_input()
input()
sys.stdin.readline()

raw_input( )將所有輸入作為字符串看待,返回字符串類型
input( )只能接收“數字”的輸入,返回所輸入的數字的類型( int, float )
sys.stdin.readline()將所有輸入視為字符串,並在最后包含換行符'\n',可以通過sys.stdin.readline().strip('\n')去掉換行符。

示例

import sys
a = input("input a: ")
b = raw_input("raw_input b: ")
c = sys.stdin.readline()
print(a,type(a))
print(b,type(b))
print(c,type(c))

輸出:

input a: 12
raw_input b: 23
34
(12, <type 'int'>)
('23', <type 'str'>)
('34\n', <type 'str'>)

python3.x

python3.x對raw_input( )和input( )進行了整合,去除了raw_input( ),僅保留了input( )函數,接收任意輸入,將所有輸入默認為字符串處理,並返回字符串類型。

示例

import sys
a = input("input a: ")
c = sys.stdin.readline()
print(a,type(a))
print(b,type(b))
print(c,type(c))

輸出:

input a: 12
34
('12', <type 'str'>)
('34\n', <type 'str'>)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM