
面向物件Python - 檔案和字串
字串
字串是每種程式語言中最常用的資料型別。為什麼?因為我們比數字更瞭解文字,所以在寫作和交談中我們使用文字和單詞,同樣在程式設計中我們也使用字串。在字串中,我們解析文字、分析文字語義並進行資料探勘——所有這些資料都是人類可讀的文字。Python中的字串是不可變的。
字串操作
在Python中,字串可以用多種方式標記,可以使用單引號(’)、雙引號(“)甚至三引號('''),用於多行字串。
>>> # String Examples >>> a = "hello" >>> b = ''' A Multi line string, Simple!''' >>> e = ('Multiple' 'strings' 'togethers')
字串操作非常有用,並且在每種語言中都廣泛使用。程式設計師通常需要分解字串並仔細檢查它們。
字串可以迭代(逐個字元)、切片或連線。語法與列表相同。
str類在其上有很多方法,可以更容易地操作字串。dir和help命令在Python直譯器中提供瞭如何使用它們的指導。
以下是一些我們常用的常用字串方法。
序號 | 方法及描述 |
---|---|
1 | isalpha() 檢查所有字元是否都是字母 |
2 | isdigit() 檢查數字字元 |
3 | isdecimal() 檢查十進位制字元 |
4 | isnumeric() 檢查數字字元 |
5 | find() 返回子串的最高索引 |
6 | istitle() 檢查標題大小寫的字串 |
7 | join() 返回連線的字串 |
8 | lower() 返回小寫字串 |
9 | upper() 返回大寫字串 |
10 | partition() 返回一個元組 |
11 | bytearray() 返回給定位元組大小的陣列 |
12 | enumerate() 返回一個列舉物件 |
13 | isprintable() 檢查可列印字元 |
讓我們嘗試執行幾個字串方法:
>>> str1 = 'Hello World!' >>> str1.startswith('h') False >>> str1.startswith('H') True >>> str1.endswith('d') False >>> str1.endswith('d!') True >>> str1.find('o') 4 >>> #Above returns the index of the first occurence of the character/substring. >>> str1.find('lo') 3 >>> str1.upper() 'HELLO WORLD!' >>> str1.lower() 'hello world!' >>> str1.index('b') Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> str1.index('b') ValueError: substring not found >>> s = ('hello How Are You') >>> s.split(' ') ['hello', 'How', 'Are', 'You'] >>> s1 = s.split(' ') >>> '*'.join(s1) 'hello*How*Are*You' >>> s.partition(' ') ('hello', ' ', 'How Are You') >>>
字串格式化
在Python 3.x中,字串的格式化已經改變,現在它更符合邏輯並且更靈活。可以使用format()方法或%符號(舊樣式)在格式字串中進行格式化。
字串可以包含文字文字或由大括號{}分隔的替換欄位,每個替換欄位可以包含位置引數的數字索引或關鍵字引數的名稱。
語法
str.format(*args, **kwargs)
基本格式化
>>> '{} {}'.format('Example', 'One') 'Example One' >>> '{} {}'.format('pie', '3.1415926') 'pie 3.1415926'
下面的例子允許重新排列顯示順序而不改變引數。
>>> '{1} {0}'.format('pie', '3.1415926') '3.1415926 pie'
填充和對齊字串
可以將值填充到特定長度。
>>> #Padding Character, can be space or special character >>> '{:12}'.format('PYTHON') 'PYTHON ' >>> '{:>12}'.format('PYTHON') ' PYTHON' >>> '{:<{}s}'.format('PYTHON',12) 'PYTHON ' >>> '{:*<12}'.format('PYTHON') 'PYTHON******' >>> '{:*^12}'.format('PYTHON') '***PYTHON***' >>> '{:.15}'.format('PYTHON OBJECT ORIENTED PROGRAMMING') 'PYTHON OBJECT O' >>> #Above, truncated 15 characters from the left side of a specified string >>> '{:.{}}'.format('PYTHON OBJECT ORIENTED',15) 'PYTHON OBJECT O' >>> #Named Placeholders >>> data = {'Name':'Raghu', 'Place':'Bangalore'} >>> '{Name} {Place}'.format(**data) 'Raghu Bangalore' >>> #Datetime >>> from datetime import datetime >>> '{:%Y/%m/%d.%H:%M}'.format(datetime(2018,3,26,9,57)) '2018/03/26.09:57'
字串是Unicode
字串作為不可變Unicode字元的集合。Unicode字串提供了建立可在任何地方工作的軟體或程式的機會,因為Unicode字串可以表示任何可能的字元,而不僅僅是ASCII字元。
許多IO操作只知道如何處理位元組,即使位元組物件指的是文字資料。因此,瞭解如何在位元組和Unicode之間進行交換非常重要。
將文字轉換為位元組
將字串轉換為位元組物件稱為編碼。有許多編碼形式,最常見的是:PNG;JPEG,MP3,WAV,ASCII,UTF-8等。這(編碼)也是一種以位元組表示音訊、影像、文字等的格式。
可以透過encode()進行這種轉換。它以編碼技術作為引數。預設情況下,我們使用'UTF-8'技術。
>>> # Python Code to demonstrate string encoding >>> >>> # Initialising a String >>> x = 'TutorialsPoint' >>> >>> #Initialising a byte object >>> y = b'TutorialsPoint' >>> >>> # Using encode() to encode the String >>> # encoded version of x is stored in z using ASCII mapping >>> z = x.encode('ASCII') >>> >>> # Check if x is converted to bytes or not >>> >>> if(z==y): print('Encoding Successful!') else: print('Encoding Unsuccessful!') Encoding Successful!
將位元組轉換為文字
將位元組轉換為文字稱為解碼。這是透過decode()實現的。如果我們知道用於編碼它的編碼,我們可以將位元組字串轉換為字元字串。
因此,編碼和解碼是逆過程。
>>> >>> # Python code to demonstrate Byte Decoding >>> >>> #Initialise a String >>> x = 'TutorialsPoint' >>> >>> #Initialising a byte object >>> y = b'TutorialsPoint' >>> >>> #using decode() to decode the Byte object >>> # decoded version of y is stored in z using ASCII mapping >>> z = y.decode('ASCII') >>> #Check if y is converted to String or not >>> if (z == x): print('Decoding Successful!') else: print('Decoding Unsuccessful!') Decoding Successful! >>>
檔案I/O
作業系統將檔案表示為位元組序列,而不是文字。
檔案是磁碟上用於儲存相關資訊的命名位置。它用於永久地將資料儲存在您的磁碟中。
在Python中,檔案操作按以下順序進行。
- 開啟檔案
- 讀取或寫入檔案(操作)。開啟檔案
- 關閉檔案。
Python使用適當的decode(或encode)呼叫包裝傳入(或傳出)的位元組流,因此我們可以直接處理str物件。
開啟檔案
Python有一個內建函式open()來開啟檔案。這將生成一個檔案物件,也稱為控制代碼,因為它用於根據需要讀取或修改檔案。
>>> f = open(r'c:\users\rajesh\Desktop\index.webm','rb') >>> f <_io.BufferedReader name='c:\\users\\rajesh\\Desktop\\index.webm'> >>> f.mode 'rb' >>> f.name 'c:\\users\\rajesh\\Desktop\\index.webm'
要從檔案中讀取文字,我們只需要將檔名傳遞給函式即可。檔案將被開啟以進行讀取,並且位元組將使用平臺預設編碼轉換為文字。