我的python3学习笔记
2015-11-07 本文已影响962人
zty5678
windows下安装pip
安装好python之后,pip也就安装好了,但是需要把D:\Program Files\Python34\Scripts加到环境变量Path里,这样就能直接使用pip命令了,例如"pip install Pillow".
判断字符串是否为数字:
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")
字符串转换大小写
import os
a="abcdEFG"
print(a.upper())
print(a.lower())
os.system("pause")
截取字符串,以及浮点数向上取整和向下取整
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")
翻转字符串
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")
过滤字符串,只留下字母和数字
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")
判断list是否为空,是否有元素
#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()