python字符串去头尾_悉尼大学某蒟蒻的Python学习笔记
About me
本蒟蒻是悉尼大學(xué)計(jì)算機(jī)科學(xué)大一的學(xué)生,這篇博客記錄了學(xué)習(xí)INFO1110這門課的一些心得,希望能對(duì)大家有幫助。
To start with
因?yàn)橛?jì)算機(jī)只能識(shí)別機(jī)器語(yǔ)言,所以我們需要編譯器將其他語(yǔ)言翻譯成機(jī)器語(yǔ)言。編譯器有編譯(complier)和解釋(interpreter)兩種。python是屬于解釋型語(yǔ)言。
- 編譯型語(yǔ)言:程序在執(zhí)行前需要一個(gè)專門的編譯過程,把程序編譯成機(jī)器語(yǔ)言的文件,運(yùn)行時(shí)不需要重新翻譯,直接使用編譯的結(jié)果。效率高,跨平臺(tái)略差
- 解釋型語(yǔ)音:編寫的程序不進(jìn)行預(yù)先編譯,以文本方式儲(chǔ)存代碼,會(huì)將代碼一句一句直接運(yùn)行。要先解釋再運(yùn)行
Python的安裝網(wǎng)上教程很多,這里不再贅述
執(zhí)行python的兩種方式
1. 解釋器運(yùn)行
用記事本(e.g. sublime)寫好文件,保存在本地(記得文件要以.py結(jié)尾,這能讓計(jì)算機(jī)知道這是一個(gè)python文件),在終端輸入:
//python3 文件名.py python3 hello.py你也可以編譯python文件:
python -m py_compile HelloWorld.py //This makes a .pyc file for your program. The class file is called HelloWorld.class python HelloWorld.pyc2. 交互式運(yùn)行:
在終端輸入python3進(jìn)入Python環(huán)境,不需要輸入要執(zhí)行的文件名,多用于驗(yàn)證局部語(yǔ)法或代碼,但不能保持和運(yùn)行過大程序 。輸入exit()退出環(huán)境
3. IDE(集成開發(fā)環(huán)境):
集成了開發(fā)開發(fā)軟件需要的工具包括圖形界面,代碼編輯器,解釋器,調(diào)試器,比較常用的是pycharm。
變量
變量類型:
- 數(shù)字型:
int: 整數(shù), e.g. 10
bool: 布爾,e.g. 0,1,True, False
float: 浮點(diǎn)數(shù)/小數(shù),e.g. 0.5
- 非數(shù)字型
str:字符串
list: 列表
tuple: 元組
dict: 字典
Python允許你同時(shí)為多個(gè)變量賦值
a = b = c = 1 print(a) # 1 print(b) # 1也可以為多個(gè)對(duì)象指定多個(gè)變量。
a, b, c = 1, 2, "Joe" print(a) # 1 print(c) # Joe注釋
注釋里的代碼不會(huì)被執(zhí)行。
快捷鍵:sublime和vscode里,選中要注釋的代碼(一行的話可以 ctrl+L),ctrl+/ 一鍵注釋
# 這是一個(gè)當(dāng)行注釋,不會(huì)被運(yùn)行 ''' 這是一個(gè)多行注釋 程序員最討厭兩件事: 第一是寫注釋 第二是別人不寫注釋 '''字符串
合并字符串
用+號(hào)把兩個(gè)字符串連接起來
first_name=“Joe” last_name=“He” full_name=first_name+" "+last_name print(full name) //Joe He修改字符串大小寫
str.title(): 字符串內(nèi)所有的首字母母大寫, 注意are’t會(huì)變成Are’T
str.capitalize(): 字符串的第一個(gè)單詞的首字母大寫, “there is a tree” -> “There is a tree”
str.upper(): 字符串的所有單詞大寫
str.lower(): 字符串的所有單詞小寫
name="joe he" print(name.title()) //Joe Heprint(name.capitalize()) //Joe heprint(name.upper()) //JOE HEprint(name.lower())//joe he轉(zhuǎn)義字符
Python識(shí)別字符串時(shí),以 ’ (quote) 開頭,以 ’ 結(jié)尾。 如果文字中有 ’ 或 ‘’ 會(huì)導(dǎo)致python無法讀完全部文字。e.g. ‘I’am OK.’。這時(shí)候我們需要轉(zhuǎn)義字符
// 轉(zhuǎn)義 print('I'm ok.') // 制表符 (tab)t print("tpython") // 換行符 n print("JannFebnMarnAprnMaynJunnJulnAug" )刪除頭尾的空白
忽略新行
Python中每次print都會(huì)另起一行, 默認(rèn)是print(‘xx’, end = ‘n’),我們可以用一下方法忽略新行
print("line1 line2 line3") // line1 line2 line3print("#", end="")格式化
當(dāng)我們想把變量以某種特殊格式輸出時(shí),我們可以用格式化
//把string看做object,調(diào)用format method name = 'Joe' print("hello, {}".format(name))一些常用的格式化:
#()里可以是字符串或數(shù)字 '{} {}'.format('one', 2) #'one 2'#傳入順序可以通過數(shù)字1,2換 '{1} {0}'.format('one', 'two') #'two one'#format里套format '{:>{}}'.format('hello', 10) #' hello'#打印{} '{{{}}}'.format('hello') #{hello}String類
#10個(gè)字符框,靠右 '{:>10}'.format('test') #' test'#靠左 '{:10}'.format('test') #'test '#靠左,10位,剩余的用_補(bǔ)齊 '{:_<10}'.format('test') #'test______'#居中 '{:^10}'.format('test') #' test '#只取前幾個(gè)字符 '{:.5}'.format('xylophone') # xylop ' '{:10.5}'.format('xylophone') #'xylop 'Number類
#整數(shù) '{:d}'.format(42) #'42'#保留小數(shù)點(diǎn)后六位 '{:f}'.format(3.141592653589793) # 3.141593 #不足4位用空格補(bǔ) '{:4d}'.format(42) # ' 42'#六位,不足時(shí)0占位,保留到小數(shù)點(diǎn)后2位 '{:06.2f}'.format(3.141592653589793 #003.14 '{:+d}'.format(42) # +42 '{: d}'.format((- 23)) # -23 '{:=+5d}'.format(23) # + 23讀寫文檔
Python可以讀入并改寫文檔 (.txt等),常見的有兩種方法:
file = open('filename.txt', 'r') print(file.readline()) file.close()orwith open('filename.txt', 'r') as file:print(file.readline())這兩個(gè)區(qū)別是第一種方法最后需要 file.close(), 第二種不需要。open()的第一個(gè)參數(shù)是要打開文件的名字,第二個(gè)參數(shù)是打開的模式(常用的模式有’r’和’w’)。
read模式
讀文檔有read(), readlines(), readline()這幾種方法
// test.txt, 與py文件在同一目錄下。 deposit 5.00 withdraw 2.05 deposit 15.30 withdraw 935.50 wdeposit 500.50read()
讀取全部?jī)?nèi)容,返回一整個(gè)字符串
f = f.open('test.txt', 'r')print(f.read()) # deposit 5.00 withdraw 2.05 deposit 15.30 withdraw 935.50 deposit 500.50# 如果想返回一個(gè)數(shù)組: print(f.read().split()) # ['deposit', '5.00', 'withdraw', '2.05', ..]f.close()readline()
讀取一行,返回一個(gè)字符串
注意myfile.readline()一定要賦值給line,要不然if myfile.readline==""會(huì)跳過一行
readlines()
讀取全部?jī)?nèi)容,返回一個(gè)數(shù)組。會(huì)把行末尾的n讀進(jìn)去,所以要手動(dòng)去除
a=myfile.readlines() print(a) #['deposit 5.00n', 'withdraw 2.05n', 'deposit 15.30n', 'withdraw 935.50n', 'deposit 500.50'] lines=[] for line in a: lines.append(line.rstrip("n")) print(lines) #['deposit 5.00', 'withdraw 2.05', 'deposit 15.30', 'withdraw 935.50', 'deposit 500.50']Write模式
往file里寫內(nèi)容,會(huì)清空之前file的內(nèi)容。不想內(nèi)容被清空可以用mode 'a'
f.write()的括號(hào)里只能是字符串
數(shù)組
數(shù)組是包含多個(gè)相同類型值的連續(xù)內(nèi)存塊。通過index來訪問和修改數(shù)組中間儲(chǔ)存的值。
# 在python中數(shù)組可以存放不同類型的值 a = [1, 'hello'] print(a[0]) # 1a[0] = 'hi' print(a) # ['hi', 'hello']#在python中,兩個(gè)數(shù)組可以直接做賦值運(yùn)算 b = a print(b == a) #Ture創(chuàng)建特殊數(shù)組的幾個(gè)技巧:
a = [0]*4 print(a) #[0,0,0,0]a = list(range(5)) print(a) #[0, 1, 2, 3, 4, 5] #range(start,stop,step)[i for i in range(5)] print(a) #[0, 1, 2, 3, 4, 5]修改列表
motorcycles=['honda','yamaha','suzuki']在list中穿插一個(gè)字符串并連接起來
print('#'.join(stuff[3:5])) # Telephone#Light轉(zhuǎn)化字符串時(shí)會(huì)拆開:
組織列表
sort方法只會(huì)改變調(diào)用他的數(shù)組,沒有返回值
a=[3,2,1] b=a.sort() print(a) #[1,2,3] print(b) #None與字母順序相反:向方法傳遞參數(shù)sort(reverse=True)
2. 臨時(shí)排序
函數(shù)sorted會(huì)返回一個(gè)新的數(shù)組
a=[3,2,1] b=sorted(a) print(b) #[1,2,3]復(fù)制數(shù)組及枚舉
在函數(shù)中傳入數(shù)組時(shí),傳入的是數(shù)組的地址,所以會(huì)改變?cè)瓉淼臄?shù)組。如果不想原來的數(shù)組被改變,我們就需要復(fù)制一個(gè)新的數(shù)組。
new_list = old_list.copy() # or new_list = old_list[:] # or new_list = list(old_list)使用enumerate進(jìn)行枚舉:
notes = [50,20,10] new_collection = enumerate(notes) print(list(new_collection)) # ((0,50),(1,20),(3,5))notes = [50,20,10] for (index, v) in enumerate(notes): print("{}{}".format(v,index))或者使用zip:
indices =[0,1,2] notes = [50,20,10] new_collection = zip(indices, notes) print(list(new_collection))總結(jié)
以上是生活随笔為你收集整理的python字符串去头尾_悉尼大学某蒟蒻的Python学习笔记的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android edittext不可复制
- 下一篇: python注册用户名和密码登录_pyt