字符串是每種編程語(yǔ)言中使用的最流行的數(shù)據(jù)類(lèi)型。 這是為什么呢? 因?yàn)槲覀兝斫馕谋颈葦?shù)字更好,所以在寫(xiě)作和說(shuō)話時(shí)使用的是文本和單詞,在編程中也類(lèi)似地使用字符串。 在字符串中,我們解析文本,分析文本語(yǔ)義,并進(jìn)行數(shù)據(jù)挖掘 - 所有這些數(shù)據(jù)都是人類(lèi)消費(fèi)的文本。Python中的字符串是不可變的。
字符串操作
在Python中,對(duì)于多行字符串,可以用多種方式標(biāo)記字符串,使用單引號(hào)('),雙引號(hào)(")或甚至三引號(hào)(''')。
>>> # String Examples
>>> a = "hello"
>>> b = ''' A Multi line string,
Simple!'''
>>> e = ('Multiple' 'strings' 'togethers')
字符串操作非常有用,并且在每種語(yǔ)言中都被廣泛使用。 程序員通常需要分解字符串并仔細(xì)檢查。
字符串可以迭代(逐個(gè)字符),切片或連接。 語(yǔ)法與列表相同。
str類(lèi)有很多方法來(lái)使操作字符串更容易。 dir和help命令為Python解釋器提供了如何使用它們的指導(dǎo)。
以下是使用的一些常用的字符串方法。
| 編號(hào) | 方法 | 描述 |
|---|---|---|
| 1 | isalpha() |
檢查是否所有字符都是字母 |
| 2 | isdigit() |
檢查是否為數(shù)字字符 |
| 3 | isdecimal() |
檢查是否為十進(jìn)制字符 |
| 4 | isnumeric() |
檢查是否為數(shù)字字符 |
| 5 | find() |
返回子串的最高索引 |
| 6 | istitle() |
檢查是否為T(mén)itlecased字符串 |
| 7 | join() |
返回連接的字符串 |
| 8 | lower() |
返回字符串的小寫(xiě)形式 |
| 9 | upper() |
返回字符串的大寫(xiě)形式 |
| 10 | partion() |
返回一個(gè)元組 |
| 11 | bytearray() |
返回給定字節(jié)大小的數(shù)組 |
| 12 | enumerate() |
返回枚舉對(duì)象 |
| 13 | isprintable() |
檢查是否為可打印字符 |
讓我們嘗試運(yùn)行幾個(gè)字符串方法,
>>> 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格式的字符串已經(jīng)改變,現(xiàn)在它更符合邏輯,更靈活。 格式化可以使用format()方法或格式字符串中的%符號(hào)(舊樣式)來(lái)完成。
該字符串可以包含由大括號(hào){}分隔的文字文本或替換字段,每個(gè)替換字段可以包含位置參數(shù)的數(shù)字索引或關(guān)鍵字參數(shù)的名稱(chēng)。
語(yǔ)法
str.format(*args, **kwargs)
基本格式
>>> '{} {}'.format('Example', 'One')
'Example One'
>>> '{} {}'.format('pie', '3.1415926')
'pie 3.1415926'
下面的示例允許重新排列顯示順序而不更改參數(shù)。
>>> '{1} {0}'.format('pie', '3.1415926')
'3.1415926 pie'
填充和對(duì)齊字符串,可以將值填充到特定長(zhǎng)度。
>>> #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字符串提供了創(chuàng)建可在任何地方工作的軟件或程序的機(jī)會(huì),因?yàn)閁nicode字符串可以表示任何可能的字符,而不僅僅是ASCII字符。
許多IO操作只知道如何處理字節(jié),即使bytes對(duì)象引用文本數(shù)據(jù)。 因此,了解如何在字節(jié)和Unicode之間進(jìn)行交換非常重要。
將文本轉(zhuǎn)換為字節(jié)
將字符串轉(zhuǎn)換為字節(jié)對(duì)象稱(chēng)為編碼。 有許多形式的編碼,最常見(jiàn)的是:PNG; JPEG,MP3,WAV,ASCII,UTF-8等。此(編碼)也是一種以字節(jié)為單位表示音頻,圖像,文本等的格式。
這種轉(zhuǎn)換可以通過(guò)encode()實(shí)現(xiàn)。 它采用編碼技術(shù)作為參數(shù)。 默認(rèn)情況下,我們使用’UTF-8’技術(shù)。
>>> # Python Code to demonstrate string encoding
>>>
>>> # Initialising a String
>>> x = 'Yiibai'
>>>
>>> #Initialising a byte object
>>> y = b'Yiibai'
>>>
>>> # 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!
將字節(jié)轉(zhuǎn)換為文本
將字節(jié)轉(zhuǎn)換為文本稱(chēng)為解碼。 這是通過(guò)decode()實(shí)現(xiàn)的。 如果知道使用哪種編碼對(duì)字符串進(jìn)行編碼,可以將字節(jié)字符串轉(zhuǎn)換為字符串。
因此編碼和解碼是逆過(guò)程。
>>>
>>> # Python code to demonstrate Byte Decoding
>>>
>>> #Initialise a String
>>> x = 'Yiibai'
>>>
>>> #Initialising a byte object
>>> y = b'Yiibai'
>>>
>>> #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!
>>>
操作系統(tǒng)將文件表示為字節(jié)序列,而不是文本。
文件是磁盤(pán)上用于存儲(chǔ)相關(guān)信息的命名位置。 它用于永久存儲(chǔ)磁盤(pán)中的數(shù)據(jù)。
在Python中,文件操作按以下順序進(jìn)行。
.打開(kāi)文件Python使用適當(dāng)?shù)慕獯a(或編碼)調(diào)用包裝傳入(或傳出)字節(jié)流,以便我們可以直接處理str對(duì)象。
打開(kāi)文件
Python有一個(gè)內(nèi)置函數(shù)open()來(lái)打開(kāi)一個(gè)文件。 這將生成一個(gè)文件對(duì)象,也稱(chēng)為句柄,因?yàn)樗糜谙鄳?yīng)地讀取或修改文件。
>>> 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'
要從文件中讀取文本,只需要將文件名傳遞給函數(shù)。 將打開(kāi)該文件以進(jìn)行讀取,并使用平臺(tái)默認(rèn)編碼將字節(jié)轉(zhuǎn)換為文本。