數據類型是每一種語言的基礎,就比如說一支筆,它的墨有可能是紅色,有可能是黑色,也有可能是黃色等等,這不同的顏色就會被人用在不同的場景。Python中的數據類型也是一樣,比如說我們要描述一個人的年齡:小張今年18歲,這18就是一個整數,那么在Python語言里,我們將它定義為一個整型。我們也通過這一個例子引入Python的數據類型。
在講數據類型之前,我們先引入兩個方法,type和print,type是用來查看數據類型的,print是用來在控制台輸出的,在接下的案例都會經常用到。
那么Python的數據類型有哪些呢?
Pyhton中的數據類型主要分為:整型(int)布爾值(bool)字符串(str)元組(tuple)列表(list)字典(dict)。
一、整型(int):
現在有一個需求就是,就是我想輸出一個18,並查看我們18是不是就像上面我說的一樣,就是一個整型呢?那么我們可以這樣做:
print(18,type(18))
輸出結果:
18 <class 'int'>
從輸出結果我們就知道,這樣一個整數類型的在Pyhton里面就是一個整型。
那么整型數據類型都有哪些功能(方法)給我們使用呢?也就是說,我們用這些功能來完成什么事?
功能一:統計二進制位
def bit_length(self): """ int.bit_length() -> int #表示調用此方法返回的也是int類型的數 Number of bits necessary to represent self in binary. #返回的這個數是自身的二進制位 """ return 0
案例:
print((18).bit_length())
輸出結果:
5
18的二進制位:
print(bin(18))
輸出結果:
0b10010
結果我們看出,確實是5位
注:關於計算機進制不懂的自行度娘了
這個方法一般也不怎么用!!!
二、布爾值(bool)
就是True和False,這個沒什么要說的,需要注意的就是,bool(...)里面的參數如果是:None,"",(),[],{},0中的一個的時候,返回值是Fasle
三、字符串(str)
用' '或者" "包起來的就是一個字符串,比如:
print(type('18'),type("18"))
輸出結果都是:
<class 'str'>
功能一:將首字母變成大寫
def capitalize(self): """ S.capitalize() -> str #返回的是一個字符串 Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. #如果首字母是小寫,就將首字母變成大寫,然后再將這個字符串返回 """ return ""
案例:
print("jasonhy".capitalize())
輸出結果是:
Jasonhy
用法:比如通過網頁來生成個性名片,我們可以判斷用戶的用戶名如果是英文並且首字母是小寫,我們就可以將首字母變成大寫之后,再將數據返回,展示給用戶
功能二:大小寫轉換
def casefold(self): #3.3引入的 """ S.casefold() -> str #返回一個字符串 Return a version of S suitable for caseless comparisons.#返回一個小寫的字符串,可以對任何字符都有效 """ return ""
def swapcase(self): """ S.swapcase() -> str Return a copy of S with uppercase characters converted to lowercase and vice versa. #如果是大寫,就轉換成小寫,小寫的話就轉換成大寫 """ return ""
def lower(self): """ S.lower() -> str #返回一個字符串 Return a copy of the string S converted to lowercase.#返回一個小寫的字符串,但是只對'A-Z'有效 """ return ""
案例:
print("JASONHY".casefold())
輸出結果是:
jasonhy
print("JASONHY".lower())
輸出結果是:
jasonhy
官網文檔解釋,這兩個方法,如果其他語言中存在寫的話,lower()是沒有辦法進行轉換,比如德語中'ß'的小寫是'ss',而casefold是可以的,那么我們的解決辦法可以如果中文和英文可以繼續用lower(),其他語言的話再用casefold(),畢竟casefold()是3.3才出現的。
def upper(self): """ S.upper() -> str Return a copy of S converted to uppercase. #返回一個經轉換成大寫的字符串 """ return ""
案例:
print("jasonhy".upper())
輸出結果是:
JASONHY
用法:我們在隨機生成驗證碼的時候,有的時候生成的大寫,有的時候是小寫,有的時候是大小寫混搭,我們為了方便處理,往往是將它轉換成大寫或者小寫,然后統一處理
功能三:字符串的顯示位置
def center(self, width, fillchar=None): """ S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) #指定要顯示的總長度width,width的長度減去字符串的的長度,剩余的默認用空格填充,字符串居中顯示,如果差值小於0,那就只顯示字符串 """ return ""
def zfill(self, width): """ S.zfill(width) -> str Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated.#以0的形式在左邊填充 """ return ""
def ljust(self, width, fillchar=None): """ S.ljust(width[, fillchar]) -> str Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space).#字符串顯示在左邊 """ return ""
def rjust(self, width, fillchar=None): """ S.rjust(width[, fillchar]) -> str Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space). #字符串顯示在右邊 """ return ""
案例:
#指定width大於字符串的長度,居中
print("jasonhy".center(9,"*"))
輸出結果是:
*jasonhy*
#以0的形式左邊填充
print("jasonhy".zfill(9))
輸出結果是:
00jasonhy
#指定長度小於字符串的長度,居中
print("jasonhy".center(6,"*"))
輸出結果是:
jasonhy
#左邊顯示
print("jasonhy".ljust(9,"*"))
輸出結果是:
jasonhy**
#右邊顯示
print("jasonhy".rjust(9,"*"))
輸出結果是:
**jasonhy
功能四:統計字符出現的次數
def count(self, sub, start=None, end=None): """ S.count(sub[, start[, end]]) -> int #返回一個數字 Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. #統計一個字符串中某個字符出現的次數,start表示統計的起始位置,end表示統計的結束位置,如果start和end不傳的話,默認統計整個字符串 """ return 0
案例:
#默認情況
print("jasonhyjasonhyjasonhy".count("j"))
輸出結果是:
3
#設置起始位置
print("jasonhyjasonhyjasonhy".count("j",2,10))
輸出結果是:
1
功能五:判斷某個字符串的起始位置或結尾位置是某個字符串或某個字符
def startswith(self, prefix, start=None, end=None): """ S.startswith(prefix[, start[, end]]) -> bool #結果返回的是一個布爾值 Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. #是否某個字符串開頭,start表示從哪個位置開始算,end表示到哪個位置結束,默認是從0的位置開始 """ return False
def endswith(self, suffix, start=None, end=None): """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. #是否以某個字符串結尾 """ return False
案例:
#默認情況下
print("jasonhy".startswith("j"))
輸出結果是:
True
#規定起始位置
print("jasonhy".startswith("j",1,5))
輸出結果是:
False
#默認情況
print("jasonhy".endswith("y"))
輸出結果是:
True
#規定了起始位置
print("jasonhy".endswith("y",1,5))
輸出結果是:
False
用法:比如我們公司要對不同姓氏的員工進行歸類,這時我們就可以拿到每個員工的姓名,然后判斷他是由哪個姓開頭,只要結果返回True的,我們就可以將他歸為一類了
功能六:查找某個字符在字符串中出現的位置
def find(self, sub, start=None, end=None): """ S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. #返回這個字符出現的位置,默認返回第一次出現的位置,start表示從哪開始查找,end表示到哪結束 Return -1 on failure. #如貴這個字符查不到,結果返回-1 """ return 0
def index(self, sub, start=None, end=None): """ S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found. #和find一樣,但是如果查不到就會報錯 """ return 0
案例:
#默認查找
print("jasonhyjasonhy".find("j"))
輸出結果是:
0
#規定查找的位置
print("jasonhyjasonhy".find("j",1,8))
輸出結果是:
7
用法:既然find()和index()都是查找字符出現的位置,但是index()如果查不到程序就會掛掉,對於我們來說,我希望的是找不到,這個程序能繼續運行,而不是直接掛掉,所以一般我們用的是find()。
功能七:判斷字符串里面是否含有數字,字母,漢字
def isalnum(self): """ S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. #是否是由數字、字母、漢字組成,或者是這些的組合 """ return False
def isalpha(self): """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. #是否是由漢字、字母或這兩者組成 """ return False
def isdecimal(self): # """ S.isdecimal() -> bool Return True if there are only decimal characters in S, #是否只是由數字組成 False otherwise. """ return False
def isdigit(self): """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. #是否由數字組成 """ return False
def isnumeric(self): """ S.isnumeric() -> bool Return True if there are only numeric characters in S, # 是否由數字組成 False otherwise. """ return False
案例:
#只要是由漢字,字母,數字中的一個或者他們的組合返回就是True
print("jasonhy1970".isalnum())
輸出結果是:
True
#是否只是又漢字和字母組成,是的話就返回True
print("jasonhy1970".isalpha())
輸出結果是:
False
從上面的功能中,我們發現isdecimal() isdigit() isnumeric()都是用來判斷數字的,那它們有什么區別呢?
print("1".isdigit()) print("1".isdecimal()) print("1".isnumeric())
阿拉伯數字的情況下,這三者的輸出結果都是:
True
print("一".isdigit()) print("一".isdecimal())
這兩個輸出都是:
False print("一".isnumeric())
輸出結果是:
True
從上面的結果,我們發現isnumeric()情況下,阿拉伯數字和漢語下的數字都是返回True,而在漢語數字的情況下,isdigit()和isdecimal()返回的是False,還有文檔說明,羅馬數字下isdigit()返回的是True,isdecimal()返回的是False,由於本人在羅馬數字的情況下測試不出想要的結果,所以在這里就不做演示了,我們需要知道的一點就是,只要數字,用isnumeric()來做判斷,返回的都是True
用法:用戶在設置密碼的時候,我們希望用戶的密碼設置不要過於簡單,比如全是數字或全是字母,我們可用isalpha()是否都是字母和isnumeric()是否都是數字,如果符合這兩種情況下的一種,我們就給用戶一個提示,說“設置的密碼過於簡單,密碼應該包含字母,數字”等等
功能八:制表
def expandtabs(self, tabsize=8): """ S.expandtabs(tabsize=8) -> str Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. #通過tabsize來計數,如果在計數的過程中,遇到'\t'的話,就以空補齊 """ return ""
案例:
#制作一個姓名和年齡對應的表格
print("name\tage\njasonhy\t18".expandtabs(10))
輸出結果是:
name age
jasonhy 18
功能九:判斷一個字符串是否是標識符
def isidentifier(self): """ S.isidentifier() -> bool Return True if S is a valid identifier according to the language definition. #如果一個字符串按照標志符的格式的話,返回True Use keyword.iskeyword() to test for reserved identifiers such as "def" and "class". """ return False
補充:什么是標識符?
①第一個字母必須是字母或者下划線
②剩下的字符可以是數字,字母或者下划線
③區分大小寫
案例:
#定義一個run的標識符
print("run".isidentifier())
輸出結果是:
True
用法:可以通過自帶的ide來測試自己將要定義的是否是標識符,是的話,就可以用在自己的程序中,但是一般沒有必要這樣做
功能十:判斷是一個字符串中是否含有不可顯示的字符
def isprintable(self): """ S.isprintable() -> bool Return True if all characters in S are considered printable in repr() or S is empty, False otherwise. #如果一個字符串中含有不可顯示的字符時,比如'\t','\n'返回False """ return False
案例:
#含有'\t'
print("jasonhy\t18".isprintable())
輸出結果是:
False
用法:用戶在輸入電話號碼的時候,不小心按到的換行符,那么這時我們就可以提示用戶輸入了電話號碼含有其他字符,或者我們也可以判斷這種不可顯示的字符是屬於那種字符,然后用""來替換掉
功能十一:是否都是空格
def isspace(self): """ S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. #如果字符串都是空格,就返回True """ return False
案例:
#不全都是空格
print(" jasonhy".isspace())
輸出結果是:
False
用法:我們有的時候需要一個需求,就是當我們分享一些文件的時候,我們希望用戶在評論之后才能看到全部的內容,評論內容也規定了一定的字數,為了避免用戶輸入的一大串的全部空格來湊齊字數,如果用戶是在這種情況下,我就要提示用戶輸入的內容不能為空
功能十二:判斷是否是標題以及標題轉換
def istitle(self): """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. #如果字符串的首字母是大寫並且其他的都是小寫,返回True Return False otherwise. """ return False
def title(self): """ S.title() -> str Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case. #將字符串的首字母變成大寫,其他全都變成小寫 """ return ""
案例:
#首字母是大寫,但是其他有大寫的情況
print("JasoNhy".istitle())
輸出結果是:
False
#通過title()來進行轉換
print("JasoNhy".title().istitle())
輸出結果是:
True
功能十三:字符串連接和分割
def join(self, iterable): """ S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. #將一個字符串添加到一個可迭代的字符串里面,這個字符串將會在每個可迭代的字符串的字符之間 """ return ""
def split(self, sep=None, maxsplit=-1): """ S.split(sep=None, maxsplit=-1) -> list of strings #返回的是一個字符串的列表 Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. #通過字符串中的某一個字符或字符串對這個字符串進行切割,被用來切割的字符串或字符不會出現在字符串列表中,如果指定maxsplit,也就是切割數,來進行切割,如果這個切割數超過這個字符串中被選中切割的字符出現的次數,則按照被選中字符出現的次數進行切割,這時候這個切割數就不起作用了 """ return []
def partition(self, sep): """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings.#也是用來切割的,被選中的字符切割之后還存在在元組中,得到的元組主要分為三段,頭-被選中切割的字符-尾,從左邊開始查找切割字符 """ pass
def rpartition(self, sep): """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. #從右邊查找切割字符 """ pass
案例:
#用×將字符串隔開
print("*".join("jasonhy"))
輸出結果是:
j*a*s*o*n*h*y
#拼接元組里面的字符串(元組后面會講到)
print(" ".join(("my","name","is","jasonhy")))
輸出結果是:
my name is jasonhy
#拼接列表里面的字符串(列表后面會講到)
print(" ".join(["my","name","is","jasonhy"]))
輸出結果是:
my name is jasonhy
#默認切割
print("jasonhyjasonhy".split("s"))
輸出結果是:
['ja', 'onhyja', 'onhy']
#指定切割數
print("jasonhyjasonhy".split("s",1))
輸出結果是:
['ja', 'onhyjasonhy']
#三段式切割,從左邊開始查找
print("jasonhyjasonhy".partition("s"))
輸出結果是:
('ja', 's', 'onhyjasonhy')
#三段式切割,從右邊開始查找
print("jasonhyjasonhy".rpartition("s"))
輸出結果是:
('jasonhyja', 's', 'onhy')
用法:我們在填寫興趣愛好的時候,一般情況都會填寫很多興趣,我們在提交這些興趣愛好的時候,一般都是以字符串的加逗號形式進行提交的,那么在后台進行數據處理的時候,就需要對這些字符串進行處理,這時就用split來進行切割了,","切割之后得到一個列表,我們再將這個列表返回前台;在我填寫地址信息的時候,如果我們和后台約定提交的方式是:["廣東省","廣州市","天河區"],這時候,join就有用武之地了。
功能十四:空格處理
def strip(self, chars=None): """ S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. #移除兩邊的空格 If chars is given and not None, remove characters in chars instead. #如果兩端只有其中一端有空格,或者都沒有空格,在指定chars的時候,就可以移除沒有空格的那一端 """ return ""
def lstrip(self, chars=None): """ S.lstrip([chars]) -> str Return a copy of the string S with leading whitespace removed. #移除左邊的空格 If chars is given and not None, remove characters in chars instead. #如果左邊不是空格,當chars不是空的時候,就移除chars """ return ""
def rstrip(self, chars=None): """ S.rstrip([chars]) -> str Return a copy of the string S with trailing whitespace removed. #移除右邊的空格 If chars is given and not None, remove characters in chars instead. #如果右邊沒有空格,並且chars不為空的時候,就將chars移除 """ return ""
案例:
#移除兩邊的空格
print(" 18785100000 ".strip())
輸出結果是:
18785100000
用法:我們在登錄輸入密碼的時候,有的時候不小心就多加一個空格,在后台進行數據處理的時候,就要用strip()來去除空格了,要不然用戶就認為自己的密碼錯了,怎么輸還是錯誤,這樣就不好了。
功能十五:替換
def replace(self, old, new, count=None): """ S.replace(old, new[, count]) -> str Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. #將指定的字符串替換成新的字符串,如果count指定,就按照count數來進行替換 """ return ""
案例:
#只替換一個j
print("jasonhyjasonhy".replace("j","J",1))
輸出結果是:
Jasonhyjasonhy
用法:一般用來進行正則表達式(后面講到)替換的
功能十六:生成連續數字(range函數)
#對字符串遍歷,使每個字符對應相應的索引
for item in range(len("jasonhy")): print(item,s[item])
輸出結果是:
0 j
1 a
2 s
3 o
4 n
5 h
6 y
