檔和字串

字串是每種編程語言中使用的最流行的數據類型。 這是為什麼呢? 因為我們理解文本比數字更好,所以在寫作和說話時使用的是文本和單詞,在編程中也類似地使用字串。 在字串中,我們解析文本,分析文本語義,並進行數據挖掘 - 所有這些數據都是人類消費的文本。Python中的字串是不可變的。

字串操作

在Python中,對於多行字串,可以用多種方式標記字串,使用單引號('),雙引號(")或甚至三引號(''')。

>>> # String Examples
>>> a = "hello"
>>> b = ''' A Multi line string,
Simple!'''
>>> e = ('Multiple' 'strings' 'togethers')

字串操作非常有用,並且在每種語言中都被廣泛使用。 程式員通常需要分解字串並仔細檢查。

字串可以迭代(逐個字元),切片或連接。 語法與列表相同。

str類有很多方法來使操作字串更容易。 dirhelp命令為Python解釋器提供了如何使用它們的指導。

以下是使用的一些常用的字串方法。

編號 方法 描述
1 isalpha() 檢查是否所有字元都是字母
2 isdigit() 檢查是否為數字字符
3 isdecimal() 檢查是否為十進位字元
4 isnumeric() 檢查是否為數字字符
5 find() 返回子串的最高索引
6 istitle() 檢查是否為Titlecased字串
7 join() 返回連接的字串
8 lower() 返回字串的小寫形式
9 upper() 返回字串的大寫形式
10 partion() 返回一個元組
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操作只知道如何處理位元組,即使bytes對象引用文本數據。 因此,瞭解如何在位元組和Unicode之間進行交換非常重要。

將文本轉換為位元組

將字串轉換為位元組對象稱為編碼。 有許多形式的編碼,最常見的是:PNG; JPEG,MP3,WAV,ASCII,UTF-8等。此(編碼)也是一種以位元組為單位表示音頻,圖像,文本等的格式。

這種轉換可以通過encode()實現。 它採用編碼技術作為參數。 默認情況下,我們使用’UTF-8’技術。

>>> # Python Code to demonstrate string encoding
>>>
>>> # Initialising a String
>>> x = 'zaixian'
>>>
>>> #Initialising a byte object
>>> y = b'zaixian'
>>>
>>> # 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 = 'zaixian'
>>>
>>> #Initialising a byte object
>>> y = b'zaixian'
>>>
>>> #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使用適當的解碼(或編碼)調用包裝傳入(或傳出)位元組流,以便我們可以直接處理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'

要從檔中讀取文本,只需要將檔案名傳遞給函數。 將打開該檔以進行讀取,並使用平臺默認編碼將位元組轉換為文本。


上一篇: 高級特性 下一篇: 異常和異常類