python基礎--字符串
阿新 • • 發佈:2018-03-05
情況 for slow 不可 不變 基礎 ont 輸出 個數
字符串
1、形式
單引號括起來的字符串:‘hello‘
雙引號括起來的字符串:"Hello"
三引號括起來的字符串:‘‘‘hello‘‘‘(三單引號),"""hello"""(三雙引號)
三引號括起來的字符串可以換行
2、下標(索引)
從左往右,下標從0開始;
從右往右,下標從-1開始
1 a = ‘abc‘ 2 print(a[0]) ## 輸出結果: a 3 print(a[-1]) ## 輸出結果: c
3、切片-- 相當於字符串的截取
語法:字符串[起始索引:結束索引:步長] --- 不包含結束索引的字符
列表、元祖、字符串都有切片操作!!
格式: info[開始索引:結束索引]
不包括結束索引的字符
1 info = ‘life is short, you need pyhton ‘ 2 print(info[0:4]) 3 print(info[5:]) ## 5到結束字符 4 print(info[:10]) # 開始到10 位置 5 print(info[1:10:2]) ## 2表示步長 6 print(info[::2]) ##隔一個取一個 7 print(info[::-1]) ## 倒序!!!
字符串的常用操作:
無論對字符串進行怎樣的操作,原字符串一定是不變的!!一般是生成了新的字符串
字符串的不可變性 !!
1、strip() ---- 去除空格
1 a = ‘ abc def ‘ 2 print(a.strip()) ## 去除全部空格 3 print(a.lstrip()) ## 去除左邊的空格 4 print(a.rstrip()) ## 去除右邊的空格
2、upper、lower --- 大小寫轉換
1 b = ‘abCDE‘ 2 print(a.lower()) ## 輸出結果是:abcde 3 print(a.upper()) ## 輸出的結果:ABCDE 4 5 ##判斷是否是大寫或小寫: 6 isupper()和islower()
3、endswith() startswith() --- 判斷以xx開頭或者以xx結尾
1 b= ‘ASD_234‘ 2 print(b.endswith(‘234’)) ##輸出結果是: True 3 print(b.startswith(‘AS‘)) ##輸出結果是:True
4、join() 字符串的拼接
1 print(‘‘.join([‘hello‘,‘world‘])) ##輸出的結果是:helloworld 2 3 ##更加常用的拼接方法: 4 a = ‘abc‘ 5 b = ‘efgr‘ 6 print(a+b) ## 輸出的結果是:abcefgr
5、各種常用判斷數字、字母、空格
## 判斷是否都是數字 print(‘123‘.isdigit()) print(‘123‘.isdecimal()) print(‘123‘.isnumeric()) ## 判斷是否是空格 print(‘ ‘.isapace()) ## True ## 判斷是否都是字符組成 print(‘abcdf‘.isalpha()) ## 判斷是否是有數字和字符組成 print(‘fff123‘.isalnum())
總結:以上的幾個方法都可以配合for循環,遍歷之後來一個個判斷所有字符的情況,用於統計字符的個數啥的
6、split() ----- 分割
分割後的結果不包含分割符,結果返回一個列表
1 name = ‘I love you‘ 2 print(name.split(‘ ‘)) ## 輸出的結果是:[‘I‘, ‘love‘, ‘you‘] 3 4 ## 若是分割字符不存在,就直接將字符串整體給列表 5 print(name.split(‘x‘)) ##輸出的結果是:[‘I love you‘]
1 小例子:假設輸入:10*20 求計算結果 2 shuzi = ‘10-20‘ 3 if shuzi.find(‘*‘) !=-1: ##找到了* 4 l = shuzi.split(‘*‘) ## 分割,返回的結果是:l = [‘10‘.‘20‘] 5 v = int(l[0])*int(l[1]) 6 print(V) ##輸出的結果是:200
還有一個分割:splitlines()--- 按照換行符進行分割!!
7、replace() ----- 替換
替換之後,生成了一個新的字符串,原來的字符串不變
1 ## 默認替換所有指定字符 2 info = ‘life is shorts‘ 3 print(info.replace(‘is‘,was)) ##輸出:life was shorts 4 5 ## 指定替換次數 6 print(info.replace(‘s‘,‘S‘,1)) ##輸出:life is Shorts
8、find() ----- 查找
如果存在,就返回第一個字符的索引;
如果不存在,就返回-1
1 info = ‘life is short, you need pyhton ‘ 2 print(info.find(‘is‘)) 3 print(info.find(‘iii‘)) 4 print(info.find(‘is‘,10,20)) ##指定範圍 5 6 ##index() 也是查找,若是不存在,會報異常 7 print(info.index(‘sss‘)) 8 ##指定範圍 9 print(info.index(‘is‘,4,20)) 10 11 # ##獲取指定的內容出現的次數 12 # ## 不存在返回0次 13 ## 也可以指定範圍 14 print(info.count(‘s‘)) 15 print(info.count(‘s‘,10,15))
8、format() ----- 格式化字符串
在format函數中,使用{}充當格式化操作符
1 print(‘{},{}‘.format(‘chuhao‘,20)) ##chuhao,20 2 print(‘{1},{0}‘.format(‘chuhao‘,20)) ##20,chuhao 3 print(‘{1},{0},{1}‘.format(‘chuhao‘,20)) ##20,chuhao,20
python基礎--字符串