Learning Python Part I 之 字符串

字符串——一串有序的字符用來儲存或代表文本或者位信息。

  • 在Python3.x中,有三種字符串類型: Str 用於 Unicode文本(包括 ASC II); bytes用於二進制數據(包括編碼文本); bytearray是bytes的變體,是可變的(mutable)。文件有兩種模式:通過Unicode編碼的Str文本和bytes表示的二進制數據。
  • 在Python2.x中,unicode 字符串表示Unicode文本,Str字符串處理8位文本和二進制數據。並且bytearray在2.6中也是可用的。常見的文件內容用str表示,但是codecs模塊打開Unicode文件並用unicode對象代表內容,處理解碼問題。

    從功能的角度來講,字符串能夠表示任何可以被編碼成文本或字節的信息。其中包括符號和字,這些信息被儲存在內存中,可以代表IP地址、Python源碼等。字符串也可以用來代表媒體文件和網絡傳輸的原始字節信息,並且以非ASCII碼的Unicode文本的形式編碼和解碼。
    

Python中的字符串被歸類爲不可變序列,字符串所包含的字符有從左到右的位置順序並且一經創建就不能改變。

下表是字符串基本的創建方法與基本操作:

這裏寫圖片描述

除了這些核心字符串工具外,Python通過標準庫模塊 re 也支持更加高級的基於模式的字符串處理。和更加高級的文本處理如XML解析等。進一步瞭解可以查詢Python的在線手冊。

字符串基礎

創建

' '" "均可以創建字符串,''' '''""" """用於創建多行字符串。

>>> 'shrubbery', "shrubbery"
('shrubbery', 'shrubbery')
>>> 'knight"s', "knight's"
('knight"s', "knight's")
>>> title = "Meaning " 'of' " Life" #python會自動連接字符串
>>> title
'Meaning of Life'

轉義符

這裏寫圖片描述

舉例:

>>> s = 'a\nb\tc'
>>> print(s)
a
b   c
>>> s
'a\nb\tc'
>>> s = "s\tp\na\x00m"
>>> print(s)
s   p
am

抑制轉義符

有時候文件目錄字符串中可能會包含有轉義符的形式,但是此時我們並不需要轉義:

>>> myfile = open('C:\new\text.dat', 'w') #其中包含換行符和製表符

我們可以在字符串前加一個r實現:

>>> myfile = open(r'C:\new\text.dat', 'w')

或者用雙斜槓:

>>> myfile = open('C:\\new\\text.dat', 'w')

python代碼中也可以用反斜槓表示文件路徑:

'C:/new/text.dat'

多行字符串

>>> s = """ Always look
...  on the bright
... side of life."""
>>> s
' Always look\n on the bright\nside of life.'
>>> print(s)
 Always look
 on the bright
side of life.

多行字符串的註釋

>>> s = """first      #comments here added to string
... second         #wow
... """
>>> s = (
... "first"   #comment here ignored
... "second\n"  #but newlines not automatic
... "end")
>>> print(s)
firstsecond
end

用多行字符串註釋代碼

X = 1
"""     #註釋這裏的代碼
import os
print(os.getcwd())
"""
Y = 2

基本操作

>>> len('abc')    #字符串的長度
3
>>> 'abc' + 'def'  #連接字符串
'abcdef'
>>> 'wow~' * 4     #字符串倍增
'wow~wow~wow~wow~'
>>> str = 'python'
>>> for s in str : print(s, end=' ')   #遍歷字符串
... 
p y t h o n >>>
>>> 'p' in str   #判斷字符是否在字符串中
True
>>> str[1]     #通過索引訪問特定位置的字符
'y'
>>> str[2]
't'

切片

偏移位置示意圖:

這裏寫圖片描述

>>> str = "hey! this is python"
>>> str[1:5] ,str[1:] ,str[:-1]
('ey! ', 'ey! this is python', 'hey! this is pytho')
>>> str[:]
'hey! this is python'
>>> str[::2]
'hy hsi yhn'
>>> str[1:5:2]  #第三個參數可以設置步長,如每兩個字符取一個字符
'e!'
>>> str[::-1]   #當步長爲非-1 的時候可以翻轉字符串
'nohtyp si siht !yeh'

字符串轉換

>>> num = '12'
>>> num + 2     #字符串不能和數字相加
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> int(num) + 2    #將字符串轉換爲數字
14
>>> num + str(2)  #將數字轉換爲字符串
'122'
>>> text = '1.234E-10'
>>> float(text)   #轉換爲浮點型
1.234e-10
>>> ord('s')    #s對應的ASCII碼
115
>>> chr(115)
's'
>>> int('1101', 2) #將二進制數轉換爲整數
13
>>> bin(13)     #將整數轉換爲二進制數
'0b1101'

字符串方法

這裏寫圖片描述
舉例:

>>> str = 'i am so handsome'
>>> str.split()
['i', 'am', 'so', 'handsome']
>>> str.title()     #返回字符串的標題版本
'I Am So Handsome'
>>> str.upper()     #返回字符串的大寫版本
'I AM SO HANDSOME'
>>> str.lower()     #返回字符串的小寫版本
'i am so handsome'
>>> str.swapcase() #返回大小寫交換後的版本
'I AM SO HANDSOME'
>>> s = 'string no 1'
>>> s.isalnum()   #檢查所有字符是否爲字母數字
False         #含有空格,返回false
>>> s.isalpha()   #檢查字符串中是否只有字母
False
>>> ss = '123456'
>>> ss.isalnum()
True
>>> sss='Python*is*so*cool'
>>> sss.split('*')#分割字符串可以傳遞一個參數
['Python', 'is', 'so', 'cool']
>>> '-'.join(sss)#指定字符連接多個字符串
'P-y-t-h-o-n-*-i-s-*-s-o-*-c-o-o-l'
>>> '-'.join(sss.split('*'))
'Python-is-so-cool'
>>> s = '    asdf'
>>> s.strip()#剝離字符串首尾中指定的字符,允許有一個字符串參數
'asdf'
>>> s
'    asdf'
>>> s = 'www.baidu.com'
>>> s.lstrip("wid.")#只對字符串左剝離
'baidu.com'
>>> s.rstrip("mc.d")#只對字符串右剝離
'www.baidu.co'
>>> s.rstrip("mcd")
'www.baidu.co'
>>> s.rstrip(".")
'www.baidu.com'
>>> s.find("bai")#搜索字符串中指定字符的開始位置
4
>>> s.find("google")#不存在返回 -1
-1
>>> s.startswith("www") #檢查字符串是否以www開頭
True
>>> s.endswith("com") #檢查字符串是否以com結尾
True

字符串格式化

字符串格式化的標準格式爲

%[(關鍵字)][符號][寬度][.精度]類型碼

  • 關鍵字:字典法中的索引
  • 符號:負號( - )爲右邊補全,正號( + )爲左邊補全
  • 寬度:指輸出字符的寬度
  • 精度:一般指保留幾位小數
  • 類型碼:格式化字符的類型(整數、浮點數、字符串等)

類型碼:
這裏寫圖片描述

表達式法

>>> res = 'integer: ...%d...%-6d...%6d...%06d' % (1234,1234,1234,1234)
>>> res
'integer: ...1234...1234  ...  1234...001234'
>>> x = 1.23456789
>>> '%e  |  %f   |  %g' % (x, x, x)
'1.234568e+00  |  1.234568   |  1.23457'
>>> '%E' % x
'1.234568E+00'
>>> '%-6.2f | %05.2f | %+06.1f' % (x, x, x)
'1.23   | 01.23 | +001.2'

當寬度還不確定時我們可以用 * 替位,並在之後輸入

>>> '%f, %.2f,%.*f' % (1/3.0, 1/3.0, 4, 1/3.0)
'0.333333, 0.33,0.3333'

通過字典的方法:

>>> reply = """
... Greetings...
... Hello %(name)s!
... Your age is %(age)s
... """
>>> values = {'name': 'jack', 'age': 40}
>>> print(reply % values)

Greetings...
Hello jack!
Your age is 40

>>> 

format

順序位置定位:

>>> template = '{0}, {1} and {2}'
>>> template.format('spam', 'ham', 'eggs')
'spam, ham and eggs'

關鍵詞定位:

>>> template = '{motto}, {pork} and {food}'
>>> template.format(motto='spam', pork='ham', food='eggs')
'spam, ham and eggs'

混合定位:

>>> template = '{motto}, {0} and {food}'
>>> template.format('ham', motto='spam', food='eggs')
'spam, ham and eggs'

相關位置定位:

>>> template = '{}, {} and {}'
>>> template.format('spam', 'ham', 'eggs')
'spam, ham and eggs'

format還支持更對高級的用法:

>>> import sys
>>> 'My {map[kind]} runs {sys.platform}'.format(sys = sys,map={'kind' : 'laptop'})
'My laptop runs linux'
>>> somelist = list('SPAM')
>>> somelist
['S', 'P', 'A', 'M']
>>> 'first={0[0]}, third={0[2]}'.format(somelist)
'first=S, third=A'
>>> 'first={0}, last={1}'.format(somelist[0], somelist[-1])
'first=S, last=M'
>>> parts = somelist[0], somelist[-1], somelist[1:3]
>>> 'first={0}, last={1}, middle={2}'.format(*parts)
"first=S, last=M, middle=['P', 'A']

format還有更多高級的功能,用到的時候可以查python在線手冊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章