標籤:包含 rip strip 首字母 lines hello 設定 expand format
Python中包括以下常用資料類型:數字、布爾值、 字串、列表、元組、字典、集合、collention系列
一、數字
關鍵字:int
數位常用操作方法:
a = "123"print(int(a)) #轉換成數字b = 5print(b.bit_length()) #返回表示數字時佔用的最少位元
二、布爾值
關鍵字:bool
表示真或假,True或False
為False的表示:0、””(Null 字元串)、[](空列表)、()(空元組)、{}(空字典)
為True的表示:非零的數字、非空的其他資料類型對象
三、字串
關鍵字:str
字串常用功能:
常用的字串操作方法:
1、替換操作:
test18 = "alexalexalex"print(test18.replace("ex", "bbb")) #把字串中指定的字串替換,預設把全部的替換print(test18.replace("ex", "bbb", 2)) #把字串中指定的字串替換,第三個參數指定替換其中的前幾個
2、尋找操作
str1 = " hello world "print(str1.find("o")) #在字串中尋找指定的字串,返回其下標,未找到返回-1print(str1.index("o")) #在字串中尋找指定的字串,返回其下標,未找到返回錯誤
3、字串格式化
test1 = "i am {name}, age {a}"print(test1.format(name="baihl", a=10)) #格式化輸出test2 = "i am {0}, age {1}"print(test2.format("baihl", 10)) #格式化輸出print(test1.format_map({‘name‘:"baihl", ‘a‘:10})) #使用字典方式格式化
4、分割操作
test10 = "心夢無痕"str1 = "_"print(str1.join(test10)) #表示以字串_分割字元print(" ".join(test10)) #以空格分割test15 = "absdfsnlkjsljlkj"print(test15.partition("s")) #指定以s字元從左開始分割字串,只分割一次print(test15.rpartition("s")) #指定以s字元從右開始分割字串,只分割一次print(test15.split("s", 2)) #指定以s字元從左開始分割字串,分割2次,如果沒有第二個參數,預設全部分割,分割後s不包含在分割後的字元中print(test15.rsplit("s", 2))test16 = "ajf\nadfjadfjadf\nfajdfjj"print(test16.splitlines()) #預設使用\n進行字串分割,分割後的字串中不包含\nprint(test16.splitlines(True)) #預設使用\n進行字串分割,分割後的字串中包含\nprint(test16.splitlines(False)) #同不帶參數
5、刪除空格操作:
test12 = " \nalex "print(test12.lstrip()) #刪除左邊的空格或左邊的換行print(test12.rstrip()) #刪除右邊的空格。。。print(test12.strip()) #刪除所有的空格。。。print("baihl".lstrip("bax")) #從左開始匹配,把匹配到的最長字元刪除,一次類推,輸出"ihl"
6、開始和結束判斷操作
print(strname.endswith("I")) #表示字串以什麼結尾,輸出bool值print(strname.startswith("B")) #表示字串以什麼開始
7、大小寫轉換
test11 = "Alex"print(test11.islower()) #判斷是否全是小寫print(test11.lower()) #全部轉換成小寫print(test11.isupper()) #判斷是否全是大寫print(test11.upper()) #全部轉換成大寫print(test11.swapcase()) #大小寫轉換,把字串中的大寫轉成小寫,小寫轉成大寫
8、判斷字母、數字、空格、底線:
test3 = "baihl1992"print(test3.isalnum()) #判斷字串中只包含數字或字元test5 = "Alex中2"print(test5.isalpha()) #判斷字串是否全是字元,中文也算字元test6 = "123"print(test6.isdecimal(), test6.isdigit()) #判斷是否是數字print(test6.isnumeric()) #判斷是否是數字,可以判斷中文的數字test7 = "_\n"print(test7.isidentifier()) #判斷是否是字母、數字或底線print(test7.isprintable()) #是否包含不可見字元test8 = " "print(test8.isspace()) #判斷字串是否全是空格
9、判斷標題
test9 = "Baihl Up li"print(test9.istitle()) #判斷是否是標題,標題表示字串中的所有單字首大寫print(test9.title()) #轉換成標題
10、製作表格
test4 = "hello\tworld\tbaihl"print(test4)print(test4.expandtabs(6)) #表示以tab分割,每個tab加字串的寬度為6test4 = "username\tmail\tpasswd\nbaihl\[email protected]\t123456\nhaoliang\[email protected]\t123456\n"print(test4.expandtabs(20)) #製作表格,每列為20寬度
11、其他動作
strname = "HELLO WORLD"print(strname.casefold()) #小寫轉換print(strname.lower()) #小寫轉換print(strname.center(20, "*")) #字元置中,寬度20,第二個參數可選print(strname.ljust(20,"*")) #靠左對齊print(strname.rjust(20,"*")) #靠右對齊print(strname.zfill(20)) #靠右對齊,使用0填充print(strname.count("I")) #子字串的個數print(strname.count("I",5)) #從第5個下標位置開始尋找print(strname.count("I",5,6))#設定尋找的起始位置和結束位置
Python基礎資料型別 (Elementary Data Type)