我的python3學習筆記

windows下安裝pip

安裝好python之后逆甜,pip也就安裝好了虱肄,但是需要把D:\Program Files\Python34\Scripts加到環(huán)境變量Path里,這樣就能直接使用pip命令了,例如"pip install Pillow".


判斷字符串是否為數(shù)字:

import os
print("123".isdigit())
os.system("pause")

獲得字符串長度:

import os
print(len("123"))
os.system("pause")

長字符串

import os
string = ("this is a "
          "really long long "
          "string")
print(string.isdigit())
os.system("pause")

去除首尾的空格和特殊符號

s.strip()
s.lstrip()
s.rstrip()
s.rstrip(',')

兩個字符串的與操作

import os
s1="123456"
s2="123"
print(s1 and s2)
os.system("pause")

字符串轉(zhuǎn)換大小寫

import os
a="abcdEFG"
print(a.upper())
print(a.lower())
os.system("pause")

截取字符串,以及浮點數(shù)向上取整和向下取整

import os
import math
text="12345" 
s = 0 
e = math.ceil((len(text))/2)
print(e)
e = math.floor((len(text))/2)
print(e)
print(text[s:e] )
os.system("pause")

indexOf

import os
import math
text="hello world" 
pos=text.index("wor")
print(text[pos:] )
os.system("pause")

打印字符串中的所有字符

import os
import math
text="hello world" 
for c in text:
    print(c,end=" ")
os.system("pause")

翻轉(zhuǎn)字符串

import os
import math
text="hello world" 
print(text[::-1])
os.system("pause")

以指定分割符拼接一個list中的所有項

import os
import math
seperator="."
mylist = ['jim', 'tom', 'bob', 'john']
print(seperator.join(mylist))
os.system("pause")

過濾字符串,只留下字母和數(shù)字

import os
def onlyLetterAndNumber(s):
    s2 = s.lower();
    fomart = 'abcdefghijklmnopqrstuvwxyz0123456789'
    for c in s2:
        if not c in fomart:
            s = s.replace(c,'');
    return s;
 
print(onlyLetterAndNumber("a000 aa-b"))
os.system("pause")

判斷l(xiāng)ist是否為空,是否有元素

#coding: utf-8
import os
def isListEmpty(a):
    if not a:
        print("list is empty")
    else:
        print("list is not empty")


a=["a"]
isListEmpty(a)
del a[:]  #清空list
isListEmpty(a)
os.system("pause")

生成一個有序list,再打亂

#coding: utf-8
import random
import os
# works in place
l = list(range(4))
random.shuffle(l)
print(l)
os.system("pause")

在一個list后面追加list

#coding: utf-8
import os
x = [1, 2, 3]
x.append([4, 5])  #[1, 2, 3, [4, 5]]
print(x)
x = [1, 2, 3]
x.extend([4, 5])
print(x)  #[1, 2, 3, 4, 5]
os.system("pause")
''' 
多行注釋
'''

在list中查找某個值

#coding: utf-8
import os
print(["foo","bar","baz"].index('bar'))
os.system("pause")

對list進行排序,條件是字母順序

#coding: utf-8
import os
from operator import itemgetter
list_to_be_sorted=["foo","bar","baz"]
newlist = sorted(list_to_be_sorted, key=lambda k: k) 
print(newlist)
list_to_be_sorted=[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
newlist = sorted(list_to_be_sorted, key=lambda k: k["name"]) 
print(newlist)

newlist = sorted(list_to_be_sorted, key=itemgetter('name')) 
print(newlist)
os.system("pause")

隨機從list中選取一項

#coding: utf-8
import os
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
os.system("pause")

對一個int的list進行倍乘

#coding: utf-8
import os
new_list = [i * 2 for i in [1, 2, 3]]
print(new_list)
os.system("pause")

合并2個字典

#coding: utf-8
import os
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = x.copy()
z.update(y)
print(z)
os.system("pause")

GUI

tkinter.ttk

from tkinter import *

class Application(Frame):
    def say_hi(self):
        print ("hi there, everyone!")

    def createWidgets(self):
        self.QUIT = Button(self)
        self.QUIT["text"] = "QUIT"
        self.QUIT["fg"]   = "red"
        self.QUIT["command"] =  self.quit

        self.QUIT.pack({"side": "left"})

        self.hi_there = Button(self)
        self.hi_there["text"] = "Hello",
        self.hi_there["command"] = self.say_hi

        self.hi_there.pack({"side": "left"})

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()

GUI 2

from tkinter import *
from tkinter import ttk

def calculate(*args):
    try:
        value = float(feet.get())
        meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
    except ValueError:
        pass
    
root = Tk()
root.title("Feet to Meters")

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

feet = StringVar()
meters = StringVar()

feet_entry = ttk.Entry(mainframe, width=7, textvariable=feet)
feet_entry.grid(column=2, row=1, sticky=(W, E))

ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky=W)

ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

feet_entry.focus()
root.bind('<Return>', calculate)

root.mainloop()
 

GUI 3

import tkinter as tk
from tkinter import ttk


LARGE_FONT= ("Verdana", 12)


class SeaofBTCapp(tk.Tk):

    def __init__(self, *args, **kwargs):
        
        tk.Tk.__init__(self, *args, **kwargs)

        #tk.Tk.iconbitmap(self,default='clienticon.ico')
        tk.Tk.wm_title(self, "Sea of BTC Client")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, PageOne, PageTwo):

            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

        
class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        
        label = ttk.Label(self, text="Start Page", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button = ttk.Button(self, text="Visit Page 1",
                            command=lambda: controller.show_frame(PageOne))
        button.pack()

        button2 = ttk.Button(self, text="Visit Page 2",
                            command=lambda: controller.show_frame(PageTwo))
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = ttk.Label(self, text="Page One!!!", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = ttk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = ttk.Button(self, text="Page Two",
                            command=lambda: controller.show_frame(PageTwo))
        button2.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = ttk.Label(self, text="Page Two!!!", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

        button1 = ttk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = ttk.Button(self, text="Page One",
                            command=lambda: controller.show_frame(PageOne))
        button2.pack()
        


app = SeaofBTCapp()
app.mainloop()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末交煞,一起剝皮案震驚了整個濱河市咏窿,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌素征,老刑警劉巖集嵌,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異御毅,居然都是意外死亡根欧,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進店門亚享,熙熙樓的掌柜王于貴愁眉苦臉地迎上來咽块,“玉大人,你說我怎么就攤上這事欺税〕藁Γ” “怎么了?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵晚凿,是天一觀的道長亭罪。 經(jīng)常有香客問我,道長歼秽,這世上最難降的妖魔是什么应役? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮燥筷,結(jié)果婚禮上箩祥,老公的妹妹穿的比我還像新娘。我一直安慰自己肆氓,他們只是感情好袍祖,可當我...
    茶點故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著谢揪,像睡著了一般蕉陋。 火紅的嫁衣襯著肌膚如雪捐凭。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天凳鬓,我揣著相機與錄音茁肠,去河邊找鬼。 笑死缩举,一個胖子當著我的面吹牛垦梆,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蚁孔,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼奶赔,長吁一口氣:“原來是場噩夢啊……” “哼惋嚎!你這毒婦竟也來了杠氢?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤另伍,失蹤者是張志新(化名)和其女友劉穎鼻百,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體摆尝,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡温艇,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了堕汞。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片勺爱。...
    茶點故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖讯检,靈堂內(nèi)的尸體忽然破棺而出琐鲁,到底是詐尸還是另有隱情,我是刑警寧澤人灼,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布围段,位于F島的核電站,受9級特大地震影響投放,放射性物質(zhì)發(fā)生泄漏奈泪。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一灸芳、第九天 我趴在偏房一處隱蔽的房頂上張望涝桅。 院中可真熱鬧,春花似錦烙样、人聲如沸冯遂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽债蜜。三九已至晴埂,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間寻定,已是汗流浹背儒洛。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留狼速,地道東北人琅锻。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像向胡,于是被迫代替她去往敵國和親恼蓬。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,629評論 2 354

推薦閱讀更多精彩內(nèi)容