目錄
數字
判斷是數字類型還是字符串類型。
# <class 'str'> 123
a = "123"
print(type(a), a)
# <class 'int'> 123
b = int(a)
print(type(b), b)
十進制、二進制、八進制、十六進制,搞不懂就不要在IT圈混了。
# 各個進製表示
print("十進制11,也就是:11:", 11)
print("二進制11,也就是3:", 0b11)
print("八進制11,也就是9:", 0o11)
print("十六進制11,也就是17", 0x11)
二進制、八進制、十六進制轉換爲十進制,通過改變base入參實現。
# 將十六進制數轉換爲十進制數
num = 'b'
v = int(num, base=16)
print(v)
# bit_length的用法
age = 0
while age < 0x10:
print(age, ":", age.bit_length())
age += 1
pass
布爾
布爾就是真假。真True,假Flase。
Python中True存儲爲數字1,False存儲爲數字0。
判斷真假的方法也很簡單,空值None、數字0、空字符串""、空列表[]、空元組()、空字典{}都是False,其餘的是True。
print(int(True)) # 1
print(int(False)) # 0
print(bool(None)) # False
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool(())) # False
print(bool({})) # False
字符串
字符串的常用函數
字符串可以獲取任意位置的字符,也就是字符串索引(下標),並通過下標獲取子字符串(切片)。切片都是前閉後開區間。
可以獲取字符串的長度,用len。
test = "Kevin"
# i
# vi
# Kevi
v1 = test[3]
v2 = test[2:4]
v3 = test[0:-1]
print(v1, len(v1))
print(v2, len(v2))
print(v3, len(v3))
大小寫轉換capitalize、lower、upper、casefold、swapcase
# 首字母大寫
test = "alex"
print(test.capitalize())
# 英文字母的大寫轉換爲小寫
test = "aLex"
print(test.lower())
# 更牛逼的大寫轉換爲小寫,任意字母
test = "ΘΠ"
print(test.casefold())
# 轉換大小寫
test = "θπΘΠ"
print(test.swapcase())
居中填充center、居左填充ljust、居右填充rjust、以某字符串開頭startwith、以某字符串結尾endwith、查找子字符串find等實用方法。
# 居中填充 center ***Alex**
# 居左填充 ljust Alex*****
# 居右填充 rjust *****Alex
test = "Alex"
vc = test.center(9, "*")
vl = test.ljust(9, "*")
vr = test.rjust(9, "*")
print(vc, vl, vr)
# 從第6個開始到第8個結束(不含),計算子字符串個數
test = "aLexalexer"
print(test.count("ex", 6, 8))
# 以***開頭結尾
test = "aLexalexer"
print(test.endswith("ex", 6, 8))
print(test.startswith("al", 4, 6))
# 查找子字符串
test = "aLexalexer"
print(test.find("ex"))
print(test.find("ex", 5, 7)) #[5, 8)
print(test.find("ex", 5, 8)) #[5, 8]
格式化字符串、輸出對齊格式化。
# 格式化
# i am {name}, age {a}
# i am Alex, age 19
test = "i am {name}, age {a}"
v1 = test.format(name="Alex", a=19)
v2 = test.format_map({"a": 19, "name": "Alex"})
print(v1)
print(v2)
# 格式化
# i am {0}, age {1}
# i am Alex, age 19
test = "i am {0}, age {1}"
print(test)
v3 = test.format("Alex", 19)
print(v3)
# 用expandtabs來實現對齊
# 找到\t也就是tab,將tab轉換爲空格
# tab前面的字符和轉換的空格加起來長度一致
# username email password
# lingmk [email protected] 123456
# alex [email protected] 1qaz2wsx
# Kevin [email protected] password
test = "username\temail\tpassword\nlingmk\[email protected]\t123456\nalex\[email protected]\t1qaz2wsx\nKevin\[email protected]\tpassword\n"
v = test.expandtabs(20)
print(v)
字母數字的判斷,這個比較複雜。
# is判斷
# isalpha 字符串全是字母,不含阿拉伯數字,不包含羅馬數字,不含符號
# isnumeric 字符串全是表示順序的數字字符,比如阿拉伯數字2、漢字二貳、符號②、羅馬數字Ⅱ
# islanum isalpha或isnumeric
# isdigit 字符串全是包含阿拉伯數字的字符,比如2、②
# isdecimal 字符串全是字符表示的數,比如2
#
# string isalpha isnumeric isalnum isdigit isdecimal
# 2 False True True True True
# 二 True True True False False
# 貳 True True True False False
# ② False True True True False
# two True False True False False
# Ⅱ False True True False False
# +2 False False False False False
# θπ True False True False False
twos = ["2", "二", "貳", "②", "two", "Ⅱ", "+2", "θπ"]
v = "string\tisalpha\tisnumeric\tisalnum\tisdigit\tisdecimal\n"
for s in twos:
v += s + "\t"
v += str(s.isalpha()) + "\t"
v += str(s.isnumeric()) + "\t"
v += str(s.isalnum()) + "\t"
v += str(s.isdigit()) + "\t"
v += str(s.isdecimal()) + "\n"
pass
print(v.expandtabs(10))
檢驗字符串是不是可用的變量名,是不是關鍵字。
import keyword
# isidentifier用來檢驗是否是可用的變量名
# 如果是關鍵字那麼需要用keyword.iskeyword(s)
# name isidentifier iskeyword
# π True False
# 變量 True False
# _123 True False
# val True False
# def True True
# class True True
names = ["π", "變量", "_123", "val", "def", "class"]
val = "name\tisidentifier\tiskeyword\n"
for s in names:
val += s + "\t"
val += str(s.isidentifier()) + "\t"
val += str(keyword.iskeyword(s)) + "\n"
pass
print(val.expandtabs(16))
檢驗字符串中的字符是不是可以顯示輸出的。
# 檢驗字符串中的字符是不是可以顯示輸出的
test = "abdl\tdjf\aso"
print(test)
v = test.isprintable()
print(v)
判斷是否都是空白符
# 判斷是否都是空白符
test = " \t"
v = test.isspace()
print(v)
英文標題title
# title() 將字符串每個單詞首字母大寫
# istitle判斷時候不是title
#
# this is a title line. False
# This Is A Title Line. True
# 中文標題不是首字母大寫規則 False
test = "this is a title line."
en_title = test.title()
cn_title = "中文標題不是首字母大寫規則"
vtest = test.istitle()
ven_title = en_title.istitle()
vcn_title = cn_title.istitle()
print(test, vtest)
print(en_title, ven_title)
print(cn_title, vcn_title)
join用當前字符串將另一個字符串test的每個字符間隔開來。
# join用當前字符串將另一個字符串test的每個字符間隔開來
#
# 你是風兒我是沙
# 你 是 風 兒 我 是 沙
# 你__是__風__兒__我__是__沙
test = "你是風兒我是沙"
print(test)
t1 = " "
v1 = t1.join(test)
print(v1)
t2 = "__"
v2 = t2.join(test)
print(v2)
strip去除空白符空格、\t、\n。
# strip去除空白符
#
# left alex right 20
# left alex right 18
# left alex right 17
# left alex right 15
test = " \tleft alex right\t\t "
vl = test.lstrip()
vr = test.rstrip()
v = test.strip()
print(test, len(test))
print(vl, len(vl))
print(vr, len(vr))
print(v, len(v))
# strip去除指定字符串最多匹配的部分
#
# xalex 5
# lex 3 匹配左邊xa
# xale 4 匹配右邊x
# le 2 匹配左邊xa和右邊x
test = "xalex"
s = "9axa"
vl = test.lstrip(s)
vr = test.rstrip(s)
v = test.strip(s)
print(test, len(test))
print(vl, len(vl))
print(vr, len(vr))
print(v, len(v))
maketrans和translate一起使用做字符串的對應替換。
# maketrans和translate一起使用做字符串對應替換
#
# this is the test claus.
# 37i3 i3 37e 3e33 8l4u3.
t1 = "thawsc"
t2 = "374638"
m = str.maketrans(t1, t2)
v1 = "this is the test claus."
v2 = v1.translate(m)
print(v1)
print(v2)
partition和split分割字符串。
partition固定分成3份,左一份,匹配一份,右邊一份。
split默認分割,匹配的去掉,剩下的各自成一份。可以指定分成幾份的。
# partition and split
#
# ('spli', 't', 'partition')
# ('splitparti', 't', 'ion')
# ['spli', 'par', 'i', 'ion']
# ['spli', 'partition']
# ['spli', 'par', 'ition']
# ['spli', 'par', 'i', 'ion']
# ['splitparti', 'ion']
# ['splitpar', 'i', 'ion']
test = "splitpartition"
v1 = test.partition("t")
v2 = test.rpartition("t")
v3 = test.split("t")
v4 = test.split("t", 1)
v5 = test.split("t", 2)
v6 = test.rsplit("t")
v7 = test.rsplit("t", 1)
v8 = test.rsplit("t",2)
print(v1)
print(v2)
print(v3)
print(v4)
print(v5)
print(v6)
print(v7)
print(v8)
# 只能分割換行符
#
# ['asd', 'sdf', 'dsdf']
# ['asd\n', 'sdf\n', 'dsdf\n']
test = "asd\nsdf\ndsdf\n"
v1 = test.splitlines()
v2 = test.splitlines(True)
print(v1)
print(v2)
字符串的內存分析
在Python中,字符串是不可以改變的,這一點與Java類似。如果字符串加法拼接或者調用函數,那麼返回的是一個新的字符串,也就是內存中的一塊新區域。
我們以replace函數爲例。
# 字符串替換
#
# kevinkevinkevinkevin
# kaxeinkaxeinkevinkevin
s1 = "kevinkevinkevinkevin"
s2 = s1.replace("ev", "axe", 2)
print(s1)
print(s2)
字符串練習題
寫代碼實現功能
# 寫代碼實現功能
name = "aleX"
print("name:", name)
# a.移除name變量對應的值兩邊的空格,並輸出移除後的結果
a = name.strip(" ")
print("a.移除name變量對應的值兩邊的空格,並輸出移除後的結果:", a)
# b.判斷name變量對應的值是否以"al"開頭,並輸出結果
b = name.startswith("al")
print("b.判斷name變量對應的值是否以\"al\"開頭,並輸出結果:", b)
# c.判斷name變量對應的值是否以"X"結尾,並輸出結果
c = name.endswith("X")
print("c.判斷name變量對應的值是否以\"X\"結尾,並輸出結果:", c)
# d.將name對應的值中的"l"替換成"P",並輸出結果
d = name.replace("l", "P")
print("d.將name中的\"l\"替換成\"P\",並輸出結果:", d)
# e.將name對應的值根據"l"分割,並輸出結果
e = name.split("l")
print("e.將name對應的值根據\"l\"分割,並輸出結果:", e)
# f.將name對應的值根據"l"分割,包括"l",並輸出結果
f = name.partition("l")
print("f.將name對應的值根據\"l\"分割,包括\"l\",並輸出結果:", f)
# g.將name對應的值變大寫,並輸出結果
g = name.casefold().upper()
print("g.將name對應的值變大寫,並輸出結果:", g)
# h.將name對應的值變小寫,並輸出結果
h = name.casefold()
print("h.將name對應的值變小寫,並輸出結果:", h)
# i.輸出name對應值的第2個字符
print("i.輸出name對應值的第2個字符:", name[2])
# j.輸出name對應值的前3個字符
print("j.輸出name對應值的前3個字符:")
j = name[0:3]
for item in j:
print(item)
pass
# k.輸出name對應值的後2個字符
print("k.輸出name對應值的後2個字符:")
k = name[-2:len(name)]
for item in k:
print(item)
pass
# l.輸出name對應值中"e"所在的索引位置
l = name.find("e")
print("l.輸出name對應值中\"e\"所在的索引位置", l)
# m.獲取子序列,僅不包含最後一個字符。比如oldboy,oldbo;root,roo
m = name[0:-1]
print("m.獲取子序列,僅不包含最後一個字符。比如oldboy,oldbo;root,roo:", m)
用代碼實現功能
# 用代碼實現以下功能
# a.用下劃線將列表中的每個元素拼接成字符串,li1 = "alexerictrain"
li1 = "alexerictrain"
a = "_".join(li1)
print(a)
# b.用下劃線將列表中的每個元素拼接成字符串,li2 = ["alex", "eric", "train"]
li2 = ["alex", "eric", "train"]
b = "_".join(li2)
print(b)
實現一個整數加法計算器
# 實現一個整數加法計算器
# content = input("請輸入內容:"),比如5+9, 9+ 5, 5 + 9等
content = input("請輸入內容:")
nums = content.split("+")
val = 0
for num in nums:
val += int(num.strip())
pass
print(val)
計算用戶輸入多少個十進制小數,多少個字母
# 計算用戶輸入多少個十進制小數,多少個字母
# content = input("請輸入內容:"),比如asduiaf878123jkjsfd-213928
content = input("請輸入內容:")
count_decimal = 0
count_alpha = 0
for item in content:
if item.isdecimal():
count_decimal += 1
pass
if item.isalpha():
count_alpha += 1
pass
pass
print("十進制小數:", count_decimal)
print("字母:", count_alpha)
製作模板程序,等待用戶輸入名字、地點、愛好。輸出:敬愛可親的xxx,最喜歡在xxx幹xxx。
# 製作模板程序,等待用戶輸入名字、地點、愛好
# 輸出:敬愛可親的xxx,最喜歡在xxx幹xxx。
template = "敬愛可親的{who},最喜歡在{where}幹{what}。"
who = input("請輸入名字:")
where = input("請輸入地點:")
what = input("請輸入愛好:")
val = template.format(who=who, where=where, what=what)
print(val)
製作隨機驗證碼程序
# 製作隨機驗證碼程序,不區分大小寫
# 過程
# 用戶執行程序
# 程序顯示驗證碼
# 用戶輸入驗證碼
# 用戶輸入值域驗證碼一致顯示正確,否則繼續生成驗證碼等待輸入
def check_code():
import random
checkcode = ""
for i in range(4):
current = random.randrange(0, 4)
if current != i:
temp = chr(random.randint(65, 90))
else:
temp = random.randint(0, 9)
checkcode += str(temp)
return checkcode
while True:
code = check_code()
print("驗證碼:", code)
input_code = input("請輸入驗證碼:")
if code.casefold() == input_code.strip().casefold():
print("驗證碼正確!")
break
pass
敏感詞過濾程序
# 敏感詞過濾程序,提示用戶輸入,將輸入的"蒼井空","東京熱"替換爲"***"
# 測試用的字符串可能包含蒼井空,波多野結衣,櫻心美,沖田杏梨,西條琉璃,櫻井莉亞,初音實等詞彙,她們有一部分出演了東京熱的片子
content = input("請輸入內容:")
process1 = content.replace("蒼井空", "***")
process2 = process1.replace("東京熱", "***")
print(process2)
表格顯示
# 表格顯示
# 提示用戶輸入姓名、郵箱、密碼,都不得超過20字符,超過則截取前20個字符
# 如果用戶輸入q或者Q則表示輸入結束,以表格形式打印輸入
content = "姓名\t郵箱\t密碼\n"
while True:
name = input("請輸入姓名(不得超過20字符):")
if name.casefold() == "q":
break
pass
if len(name) > 20:
content += name[0:20] + "\t"
else:
content += name + "\t"
pass
email = input("請輸入郵箱(不得超過20字符):")
if email.casefold() == "q":
break
pass
if len(email) > 20:
content += email[0:20] + "\t"
else:
content += email + "\t"
pass
password = input("請輸入密碼(不得超過20字符):")
if password.casefold() == "q":
break
pass
if len(password) > 20:
content += password[0:20] + "\n"
else:
content += password + "\n"
pass
pass
val = content.expandtabs(30)
print(val)