python字符串类型_Python3的字符串类型(疯狂Python)
先看一下本篇文章要講的內容目錄:
4.2 字符串入門String4.2.1 repr和字符串4.2.2 input和raw_input4.2.3 長字符串4.2.4 bytes4.2.5 字符串格式化4.2.6 Python自帶兩個幫助函數4.2.7 刪除多余空白4.2.8 字符串的查找,替換4.2.9 字符串的分割,連接方法4.2.9 運算符---------------------
4.2 字符串入門String
字符串的意思就是“一串字符”,比如“Hello,田心木瓜”是一個字符串。Python中的字符串用單引號 ’ 或雙引號 " 括起來,同時使用反斜杠 \ 轉義特殊字符(比如對引號進行轉義)。也可以在字符串前面添加一個 r,表示原始字符串。
【如下代碼全部在Ipython實現,后續如無特殊說明,都指在Ipython下】
In [1]: txmg = "It is a \'charcter\'." #轉義字符的使用In [2]: print (txmg)It is a 'charcter'.字符串的截取的語法格式如下:
變量[頭下標:尾下標]
索引值以 0 為開始值,-1 為從末尾的開始位置。
In [3]: ss = 'ABCDEFGHIJ' #定義一個字符串In [7]: ss[2]Out[7]: 'C'In [8]: ss[0]Out[8]: 'A'In [9]: ss[-9]Out[9]: 'B'In [10]: ss[1]Out[10]: 'B'In [11]: ss[-1]Out[11]: 'J'
加號 + 是字符串的連接符, 星號 * 表示復制當前字符串,緊跟的數字為復制的次數。實例如下:
In [13]: print (ss[0:-1]) #第一個到最后,不包含最后一個JABCDEFGHIIn [14]: print (ss[1:5]) # 輸出從第二個開始到第五個的字符BCDEIn [15]: print (ss[3:]) #輸出從第4個開始到最后DEFGHIJIn [16]: print (ss * 3) # 輸出字符串3次ABCDEFGHIJABCDEFGHIJABCDEFGHIJIn [17]: print (ss + "hhhhh") # 連接字符串ABCDEFGHIJhhhhh小結
反斜杠可以用來轉義,使用r可以讓反斜杠不發生轉義。字符串可以用+運算符連接在一起,用*運算符重復。Python中的字符串有兩種索引方式,從左往右以0開始,從右往左以-1開始。Python中的字符串不能改變。4.2.1 repr和字符串
Python不允許直接拼接數值和字符串,必須先將數值轉換成字符串。
可以使用str()或repr()函數,舉例如下:
In [18]: meat = "豬肉很貴啊,價錢是:"In [19]: price = 88.78In [20]: print (meat + price)---------------------------------------------------------------------------TypeError Traceback (most recent call last) in ----> 1 print (meat + price)TypeError: can only concatenate str (not "float") to strIn [21]: print (meat + str(price))豬肉很貴啊,價錢是:88.78In [22]: print (meat + repr(price))豬肉很貴啊,價錢是:88.784.2.2 input和raw_input
input()函數用于向用戶生成一個提示,然后獲取用戶輸入的內容,此函數總會將用戶輸入的內容放入字符串中,因此用戶輸入任何內容,input()函數總是返回一個字符串。
raw_input()是python 2中的,相當于python 3中的inputIn [27]: i = input()1In [28]: print (type(i))In [29]: j = input()2.89In [30]: print (type(j))In [31]: h = input()helloIn [32]: print (type(h))4.2.3 長字符串
‘’'三個引號一般用于多行注釋,但是也可以將它賦值,如下例子。
In [33]: ls = '''"It is a long long long....: stroy ,please read it....: are u ok?"...: '''In [34]: print (ls)"It is a long long long.stroy ,please read it.are u ok?"4.2.4 bytes
python3 新增bytes類型,str是以多個字符組成, bytes是以多個字節組成,bytes只負責以字節(二進制格式)序列來記錄數據,由于bytes保存原始的字節(二進制格式)數據,因此bytes對象可用于網絡上傳輸數據,也可用于存儲各種二進制格式的文件。比如圖片,音樂等文件。
如果字符串內容都是ASCII字符,則可直接在字符串之前添加b來構建bytes值。
調用bytes()函數,將字符串按照指定字符集轉換成bytes,默認使用UTF-8字符集。
調用字符串本身的encode() 方法將字符串按指定字符集轉換成bytes,默認使用UTF-8字符集
4.2.5 字符串格式化
Python提供了“%”對各種類型的數據進行格式化輸出,
In [35]: number = -29In [36]: print ('number is %6i' % number)number is -29In [37]: print ('number is %6d' % number)number is -29In [38]: print ('number is %6o' % number)number is -35In [39]: print ('number is %6x' % number)number is -1dIn [40]: print ('number is %6X' % number)number is -1DIn [41]: print ('number is %6S' % number)In [42]: print ('number is %6s' % number)number is -29%6 -> 6是指輸出最小寬度為6。轉換浮點數的寬度可以用%6.3f,感興趣可以自己試一下
python中字符串還支持用in運算符判斷是否包含某個子串,還有獲取字符串的長度,用內置len()函數,還可以用min()和max()函數獲取字符串中最小字符和最大字符
In [43]: ah = 'This is has two dogs.'In [44]: 'two' in ahOut[44]: TrueIn [48]: 'nn' in ahOut[48]: FalseIn [49]: len(ah)Out[49]: 21In [50]: min(ah)Out[50]: ' 'In [51]: max(ah)Out[51]: 'w'4.2.6 Python自帶兩個幫助函數
dir():列出指定類或模塊包含的全部內容(包括函數,方法,類,變量等)
help():查看某個函數或方法的幫助文檔
感興趣的可自行嘗試, 比如dir(str)
4.2.7 刪除多余空白
字符串還提供了了如下常用的方法來刪除空白
strip():刪除字符串前后的空白
lstrip():刪除字符串前面(左邊)的空白
rstrip():刪除字符串后面(右邊)的空白
注意:因為字符串類型是不可變的,所以上述三個方法是刪除空白的副本,并沒有真正改變字符串本身
In [55]: abc = " the is hh "In [56]: print (abc)the is hhIn [57]: abc.strip()Out[57]: 'the is hh'In [58]: abc.lstrip()Out[58]: 'the is hh 'In [59]: abc.rstrip()Out[59]: ' the is hh'In [60]: print (abc)the is hh還可以刪除指定字符的In [80]: s123 = 'the is hhhhhhioo'In [81]: print (s123)the is hhhhhhiooIn [82]: print (s123.lstrip('th'))e is hhhhhhiooIn [83]: print (s123.rstrip('isioo'))the is hhhhhhIn [84]: print (s123.strip('tioo'))he is hhhhhh4.2.8 字符串的查找,替換
startswith(): 判斷字符串是否以指定子串開頭。
endstwith():判斷字符串是否以指定子串結尾。
find():查找指定子串在字符串中出現的位置,如果沒有知道指定子串,則返回-1.
index():查找指定子串在字符串中出現的位置,如果沒有知道指定子串,則引發VauleError錯誤
replace():使用指定子串替換字符串中的目標子串。
translate():使用指定的翻譯映射表對字符串執行替換。
4.2.9 字符串的分割,連接方法
split(): 將字符串按指定分隔符分割成多個短語join(): 將多個短語連接成字符串
In [87]: print (a1.split()) #使用空白對字符串進行分割['crazyPython', 'is', 'a', 'good', 'book']In [88]: print (a1.split(None, 2)) #使用空白對字符串進行分割,最多只分割前兩個單詞['crazyPython', 'is', 'a good book']In [91]: print (a1.split('y')) #使用y來進行分割['craz', 'P', 'thon is a good book']In [92]: my_a1 = a1.split()In [94]: print (my_a1)['crazyPython', 'is', 'a', 'good', 'book']In [95]: print ('/'.join(my_a1))crazyPython/is/a/good/bookIn [96]: print (','.join(my_a1))crazyPython,is,a,good,book4.2.9 運算符
python運算符:
賦值運算符
算術運算符位運算符索引運算符In [97]: a10 = 'abcdefghijklmnopq'In [99]: print (a10[2:8:3]) #獲取索引2到索引8的子串,步長為3cfIn [100]: print (a10[2:8:2]) #獲取索引2到索引8的子串,步長為2ceg比較運算符
邏輯運算符三目運算符
In [101]: bb = 12In [102]: cc = 4In [103]: st = "bb 大于 cc" if bb > cc else "bb不大于cc"In [104]: print (st)bb 大于 cc
未完待續
總結
以上是生活随笔為你收集整理的python字符串类型_Python3的字符串类型(疯狂Python)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: python数据库自动重连_python
- 下一篇: java obervable_RxJav
