日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python字符串去头尾_悉尼大学某蒟蒻的Python学习笔记

發(fā)布時(shí)間:2024/1/23 python 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python字符串去头尾_悉尼大学某蒟蒻的Python学习笔记 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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.pyc

2. 交互式運(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" )

刪除頭尾的空白

  • strip():用于移除字符串頭尾指定的字符
  • rstrip(): 刪除 string 字符串末尾的指定字符
  • lstrip():用于截掉字符串左邊的空格或指定字符
  • string = ' hello ' string.strip() //'hello'favourite language = 'python ' favourite language.rstrip() //'python' number = 'foo123' number.rstrip('0123456789') //'foo'

    忽略新行

    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.50

    read()

    讀取全部?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ì)跳過一行

    with open('test.txt','r') as myfile: while True: line=myfile.readline()if line=="": breakprint(line,end="") # deposit 5.00 withdraw 2.05 deposit 15.30 withdraw 935.50 deposit 500.50# 如果想返回?cái)?shù)組 with open('transactions.txt','r') as myfile: while True: line=myfile.readline().split() if line==[]: break print(line) # ['deposit', '5.00'] ['withdraw', '2.05'] ['deposit', '15.30'] ['withdraw', '935.50'] ['deposit', '500.50']

    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)里只能是字符串

    f = f.open('test.txt','w') f.write('Hello') f.close()

    數(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']
  • 在末尾添加元素
  • motorcycles.append('ducati')
  • 在列表插入元素:
  • motorcycles.insert(0,'ducati') # 方法insert在索引0處添加空間,并將值'ducati'存儲(chǔ)在這。
  • 在list末尾加另一個(gè)列表的值:
  • list.extend(list2)
  • 統(tǒng)計(jì)某個(gè)元素在列表中出現(xiàn)的次數(shù):
  • list.count()
  • 刪除元素:
  • del mortorcycles[0]
  • 刪除元素并接著使用它的值:pop()刪除列表末尾的元素,并能接著使用它。在括號(hào)里輸入索引,刪除列表中的任意元素
  • motorcycles=['honda','yamaha','suzuki'] last_ownd=motorcycles.pop() print("The last motorcycle I owned was a"+last_owned.title()+".") # suzuki儲(chǔ)存在last_owned中
  • 根據(jù)值刪除元素:
  • motorcycles.remove('ducati')
  • 連接數(shù)組形成字符串
  • stuff = ['Apples', 'Oranges', 'Crows' ,'Telephone'] print(' '.join(stuff)) # Apples Oranges Crows Telephone

    在list中穿插一個(gè)字符串并連接起來

    print('#'.join(stuff[3:5])) # Telephone#Light
  • list():轉(zhuǎn)化成列表, 必須是iterable才能轉(zhuǎn)化,數(shù)字就不行
    轉(zhuǎn)化字符串時(shí)會(huì)拆開:
  • test = list('cat') test ['c', 'a', 't']
  • 確認(rèn)一個(gè)元素是否在數(shù)組內(nèi)
  • a=[1,2,3] print(1 in a) #true

    組織列表

  • 永久性排序-按字母順序
  • cars=['bmw','audi','toyota','subaru'] cars.sort() print(cars)

    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í)排序

    cars=['bmw','audi','toyota','subaru'] print(sorted(cars))

    函數(shù)sorted會(huì)返回一個(gè)新的數(shù)組

    a=[3,2,1] b=sorted(a) print(b) #[1,2,3]
  • 倒著打印-永久性,想恢復(fù)再次用reverse
  • cars=['bmw','audi','toyota','subaru']cars.reverse()print(cars)

    復(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)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。