03_字符串,列表,字典
阿新 • • 發佈:2018-05-08
wan 輸入 div spl python substr dsw str center
一、字符串
(1)字符串類型的轉換
//將數值轉轉為字符串類型
num = 100 to_string = str(num)
//將字符串類型轉換為數值類型 str = "100" num = int(str)
(2)輸入,輸出字符串
//輸入 username = input("請輸入用戶名:") //輸出 print("用戶名為:%s"%username) password = input("請輸入密碼:") print("密碼為:%s"%password)
(3)組成字符串的兩種方式
//方式1
A = 100 B = 200 C = A +B //結果為300 a = ‘lao‘ b = ‘wang‘ e = "===" + a + b + "===" //結果為 ‘===laowang===‘
//方式2 f = ‘===%s===‘%(a+b) //結果為‘===laowang===‘
(4)字符串中的下標
字符串中的元素下標從0開始
name = ‘abcdef‘ name[0] //值為‘a‘ name[1] //值為‘b‘
//判斷字符串的長度 name = ‘abcdef‘ length = len(name) //長度為6
//從字符串最後往前取 name = ‘abcdef‘ name[-1] //值為‘f‘ name[-2] //值為‘e‘ //或者 name[len(name)-1] //值為‘f‘
(5)切片,字符串逆序(倒序)
//切片
name = ‘abcdefABCDEF‘ name[2:5] //結果為‘cde‘,包左不包右 name[2:-2] //‘cdefABCD‘ name[2:0] //‘‘ name[2:] //‘cdefABCDEF‘ name[2:-1] //‘cdefABCDE‘ name[2:-1:2] //[起始位置:終止位置:步長],結果為‘ceACE‘
//倒序 name = ‘abcdefABCDEF‘ name[-1::-1] //-1為最後,:為第一個,步長為-1才能取到結果,結果為‘FEDCBAfedcba‘ name[::-1] //‘FEDCBAfedcba‘
(7)字符串常見操作
字符串查找<find><index>
myStr = ‘hello world itcast and itcast xxxcpp‘ myStr.find(‘world‘) //結果為6,查找world在myStr的開始位置 myStr.find(‘dongge‘) //找不到時為-1 myStr.find(‘itcast‘) //12,找到‘itcast‘第一次出現的位置 myStr.rfind(‘itcast‘) //23,從右邊開始找‘itcast‘
myStr = ‘hello world itcast and itcastxxxcpp‘ myStr.index(‘world‘) //6 myStr.index(‘donge‘) //找不到時返回 substring not found myStr.rindex(‘itcast‘ ) //23,從右邊開始找
統計次數<count>
myStr = ‘hello world itcast and itcastxxxcpp‘ myStr.count(‘itcast‘) //2
替換<replace>
myStr = ‘hello world itcast and itcastxxxcpp‘ myStr.replace(‘world‘,‘WORLD‘) //‘hello WORLD itcast and itcastxxxcpp‘ myStr //結果不會變,因為字符串不可變 myStr.replace(‘itcast‘,‘xxx‘) //‘hello world xxx and xxxxxxcpp‘ itcast被全替換成xxx myStr.replace(‘itcast‘,‘xxx‘,1) //‘hello world xxx and xxxxxxcpp‘,只替換第1次出現的itcast
切割<split>
myStr = ‘hello world itcast and itcastxxxcpp‘ myStr.split(" ") //[‘hello‘,‘world‘,‘itcast‘,‘and‘,‘itcastxxxcpp‘]
字符串中第一字符大寫<capitalize>
myStr = ‘hello world itcast and itcastxxxcpp‘ myStr.captialize() //‘Hello world itcast and itcastxxxcpp‘
字符串中每個單詞首字母大寫<title>
a = ‘hello itcast‘ a.title() //‘Hello Itcast‘
檢查是否以某字符串開頭,返回為True或False <startswith>
myStr = ‘hello world itcast and itcastxxxcpp‘ myStr.startswith(‘hel‘) //True myStr.startswith(‘eee‘) //False
檢查是否以某字符串開頭,返回為True或False <endswith>
myStr = ‘hello world itcast and itcastxxxcpp‘ myStr.endswith(‘pp‘) //True myStr.endswith(‘ppp‘) //False
將所有大寫轉為大寫 <lower>
myStr.lower()
將所有小寫轉為小寫 <upper>
myStr.upper()
將字符串居中顯示 <center>
myStr.center(50) //50為總的字符串長度
將字符串靠左顯示 <ljust>
myStr.ljust(50)
將字符串靠右顯示 <ljust>
myStr.ljust(50)
刪除字符串左邊空格 <lstrip>
myStr.lstrip()
刪除字符串右邊空格 <rstrip>
myStr.rstrip()
刪除字符串兩邊空格 <strip>
myStr.strip()
以字符串分割字符串 <partition>
03_字符串,列表,字典