1. 程式人生 > 其它 >python學習筆記--NO.1輸入輸出

python學習筆記--NO.1輸入輸出

NO.1 輸入輸出


本文是學習Python速查手冊的筆記,如有不對請指教

一、input( )函式

1. 語法

input(prompt)

input()函式接受所有使用者輸入內容,返回一個字串

在python3.7中所有的輸入都是作為字串被讀取的,要改變型別需要對字串進行型別轉換。

tips:ord()函式將字元轉換為對應的ASCII碼

num = int(input("輸入一個數:"))
print(num)
print(type(num))

n = input("請輸入:")
value = ord(n)
print(n + "的ASCII碼為",value)
print(type(n))

輸出結果:
輸入一個數:1 1 <class 'int'> 請輸入:2 2的ASCII碼為 50 <class 'str'>

2. 常用方法

2.1 常用輸入

prompt可以為空(不提示任何資訊)
也可以加轉義字元(\n表示換行)

2.2 去除輸入的非法字元

使用字串函式strip()、lstrip()、rstrip()方法

方法作用
strip()去除兩邊字元
lstrip()去除左邊字元
rstrip()去除右邊字元

tips:傳入的是一個字元陣列,編譯器去除兩端所有相應的字元,直到沒有匹配的字元。一般使用空格較多。

#實際上是刪除兩邊開始與['s','a','y']內匹配的所有字元
#直到匹配不到停止 theString = 'saaaay yes no yaaaass' print(theString.strip('say')) print(theString.strip('say '))#say後面有空格 print(theString.lstrip('say')) print(theString.rstrip('say')) 輸出結果: yes no es no yes no yaaaass saaaay yes no

2.3 多資料輸入

1.使用字串split()方法進行分割

方法作用
split()通過指定分隔符對字串進行切片

如果引數 num 有指定值,則分隔 num+1 個子字串

a,b,c = input("輸入3個字元,用逗號分隔:\n").split(",")#不限定輸入型別
m,n = map(int,input("輸入2個數字,用空格分隔:").split())#限定int型別
print(a,b,c)
print(m,n)

結果:
輸入3個字元,用逗號分隔:
q,w,e
輸入2個數字,用空格分隔:1 2
q w e
1 2
#有限定時輸入若錯誤返回ValueError

map()方法是一種函式-值的對映

2.使用迴圈實現一行多值輸入

sum = 0
for i in input("請輸入:用空格分隔:\n").split(" "):
    sum += int(i)
print(sum)

結果:
請輸入:用空格分隔:
1 2 3 4 5
15

2.4 強制轉換輸入(含字母大小寫方法)

1.int(),float(),str()等強制轉換型別

n = input("輸入1:")
int(n)
print(type(n))

m = int(input("輸入2:"))
print(type(m))

結果:
輸入1:1
<class 'str'>
輸入2:2
<class 'int'>

2.字母大小寫轉換

方法作用
upper()字串全大寫
capitalize()字串首字母大寫
title()字串每個單詞首字母大寫
lower()字串全小寫
words = "zhan lang"
print(words.title())
print(words.capitalize())
print(words.upper())

結果:
Zhan Lang
Zhan lang
ZHAN LANG

2.5 對輸入資料驗證

方法作用
isalnum()所有字元都是字母或者數字
isalpha()所有字元都是字母
isdigit()所有字元都是數字
isupper()所有字元都是大寫字母
islower()所有字元都是小寫字母
istitle()所有單詞都是大寫
isspace()所有字元都是空白、\t、\n、\r

這些方法的返回值都是bool型別

if input('輸入').isdigit():
	print("xx")
else:
	pass

字串的方法簡單但是有時不夠靈活
所以可以使用ASCII碼進行驗證,配合ord()方法

二、open( )函式–檔案

1. 語法

open(file, mode=‘r’, buffering=None, encoding=None, errors=None, newline=None, closefd=True)

file:必填引數,檔案路徑(引號括起來)

mode:可選引數,指定檔案開啟模式

說明
ropen for reading (default)
wopen for writing, truncating the file first
xcreate a new file and open it for writing
aopen for writing, appending to the end of the file if it exists
bbinary mode
ttext mode (default)
+open a disk file for updating (reading and writing)
Uuniversal newline mode (deprecated)

buffering:可選引數,指定讀寫檔案的緩衝模式
encoding:檔案編碼模式,預設UTF-8
errors:遇到錯誤的報錯嚴格程度
newline:區分換行符
closefd:傳入file引數型別

2. 檔案基本操作

首先明確,檔案中操作都是依靠指標移動的

方法作用
read(size)讀取整個檔案並返回,size表示讀取字元數,為0時預設讀取整個檔案
readline(size)讀取某行檔案內容並返回,size表示讀取此行多少字元
readlines()讀取每行檔案內容並返回一個列表
write(obj)將內容obj寫入檔案 ,前提是w或a模式開啟
tell()返回檔案指標當前位置
seek(offset,whence)移動檔案指標,offset指定移動字元個數,whence指定開始移動位置,0表示從頭開始,1表示從當前位置開始,2表示中檔案為開始,預設為0
close()關閉檔案
fp = open(r"fff.txt")
print(fp.readline(4)+'\n***************')
print(fp.read()+'\n***************')

結果:
this
***************
 is the first line
second line here
oh third
***************
#可以看到第二個read()不是從頭開始,而是從指標位置開始

例:輸出每行的前4個字元

fp = open(r"fff.txt")
while True:
    line = fp.readline(4)
    fp.readline()#讀完此行指標自動調到下一行開始
    #只用line = fp.readline(4)會連著讀,只要一行讀完才換行
    print(line)
    if line == '':
        break
fp.close()

3 常用

3.1 with open語句

with open會有一個界限,所以超出with語句會自動關閉檔案不需要呼叫close()方法

#列印每行
with open("fff.txt",'r') as f:
    lines = f.readlines()
    for line in lines:
        print(line)

3.2 多個檔案的讀取操作

除了分別讀取,賦值,列印,有一個更簡單的方法,即zip()函式

f1 = open('file1.txt','r')
f2 = open('file2.txt','r')
f3 = open('file3.txt','r')
for i,j,k in zip(f1,f2,f3):#讀取每個檔案的內容
    print(i,j,k)

3.3 讀取一個資料夾下所有檔案

遍歷該目錄下所有檔案,迴圈讀取每個檔案的內容到列表,最後將每個檔案的內容新增到列表。

import os #檔案與系統操作模組
path = '.temp/mr'#相對地址
names = os.listdir(path)#獲取目錄下所有檔案的名稱列表
all = []
for item in names:
    f = open(path+'/'+item)#讀取每個檔案
    new = []#儲存單個檔案內容
    for i in f:
        new.append(i)
    all.append(new)
for i in all:
    print(i)#遍歷輸出

三、print( )函式

1.語法

print(value, … , sep=’ ‘, end=’\n’, file=None)

value:要輸出的值,可以各種型別的變數
:列印多個值用分隔",“打印出來預設是空格,字串可以用”+"連線
sep:列印值時的分隔符,預設是空格
end:列印結尾的值,預設是換行符\n

tips:sep和end的引數必須是字串

2.常用

2.1 輸出字串

print("字串")#最常用
print(''' 123
456:--------------
789:--------------''')#三引號跨行輸出
print("字串1"+"字串2")#連線字串輸出
print('2021','1','1',sep='-')#輸出2021-1-1

使用chr()函式,可以根據ASCII碼輸出字元

print(chr(65))#結果是A

2.2 進位制輸出

x = 112
print("%o"%x)#使用操作符輸出八進位制數
print("%o %d %x"%(x,x,x))#使用操作符輸出八,十,十六進位制數
print(bin(x),oct(x),hex(x))#使用函式輸出二,八,十六進位制數

#綜合輸出進位制數
print("int: {0:d}, hex: {0:x}, oct:{0:o}, bin: {0:b}".format(x))
print("int: {0:#o}".format(x))

結果:
160
160 112 70
0b1110000 0o160 0x70
int: 112, hex: 70, oct:160, bin: 1110000
int: 0o160

2.3 彩色輸出

格式為
print(’\033[顯示方式;前景色;背景色m 字串 \033[0m’)

顯示方法意義
0終端預設設定
1高亮
4帶下劃線
5閃爍
7反白顯示
8不可見
前景色/背景色顏色
30/40
31/41
32/42
33/43
34/44
35/45紫紅
36/46青藍
37/47白色
print('\033[1;41;44m 字串 \033[0m')

結果:輸出結果

2.4 對齊輸出和指定位數輸出

方法作用
rjust(int,‘符號’)左對齊,數字代表字串佔位數,符號表示佔位符號
ljust(int,‘符號’)右對齊
center(int,‘符號’)中間對齊
zfill(int)固定位數輸出

format方法詳解見字串章節

2.5 標準輸入sys.stdin和標準輸出sys.stout.write()