欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python必備技巧之字符數(shù)據(jù)操作詳解

 更新時間:2022年03月23日 11:19:33   作者:Mr數(shù)據(jù)楊  
處理字符數(shù)據(jù)是編程不可或缺的一部分。Python?提供了一組豐富的運算符、函數(shù)和方法來處理字符串。包括字符串運算符、內(nèi)置函數(shù)、索引、切片和內(nèi)置方法??靵韺W(xué)習(xí)一下吧

字符串操作

字符串 + 運算符

+運算符用于連接字符串,返回一個由連接在一起的操作數(shù)組成的字符串。

>>> s = 'a'
>>> t = 'b'
>>> u = 'c'

>>> s + t
'ab'
>>> s + t + u
'abc'

>>> print('Go' + '!!!')
Go!!!

字符串 * 運算符

* 運算符創(chuàng)建字符串的多個副本。如果s是字符串并且n是整數(shù),則以下任一表達(dá)式都會返回由的n連接副本組成的字符串s。

>>> s = 'f.'

>>> s * 4
'f.f.f.f.'
>>> 4 * s
'f.f.f.f.'

乘數(shù)操作數(shù)n必須是正整數(shù)。

>>> 'f' * -8
''

字符串 in 運算符

Python 還提供了一個可以與字符串一起使用的成員運算符。如果第一個操作數(shù)包含在第二個操作數(shù)中,則in運算符返回 True 否則返回 False 。

>>> s = 'foo'

>>> s in 'That\'s food for thought.'
True
>>> s in 'That\'s good for now.'
False

用于相反的處理操作 not in 運算符。

>>> 'z' not in 'abc'
True
>>> 'z' not in 'xyz'
False

內(nèi)置字符串函數(shù)

Python 提供了許多內(nèi)置于解釋器并且始終可用的函數(shù)。

功能描述
chr()將整數(shù)轉(zhuǎn)換為字符
ord()將字符轉(zhuǎn)換為整數(shù)
len()返回字符串的長度
str()返回對象的字符串表示形式
# ord(c)
# 計算機(jī)將所有信息存儲為數(shù)字,使用了一種將每個字符映射到其代表數(shù)字的轉(zhuǎn)換方案
# 常用方案稱為ASCII。它涵蓋了您可能最習(xí)慣使用的常見拉丁字符
# ord(c)返回 character 的 ASCII 值
>>> ord('a')
97
>>> ord('#')
35

# chr(n)
# chr()做的是ord()相反的事情,給定一個數(shù)值n,chr(n)返回一個字符串
# 處理Unicode 字符
>>> chr(97)
'a'
>>> chr(35)
'#'
>>> chr(8364)
'€'
>>> chr(8721)
'∑'


# len(s)
# 返回字符串的長度。
>>> s = 'I am a string.'
>>> len(s)
14

# str(obj)
# 返回對象的字符串表示形式
# Python 中的任何對象都可以呈現(xiàn)為字符串
>>> str(49.2)
'49.2'
>>> str(3+4j)
'(3+4j)'
>>> str(3 + 29)
'32'
>>> str('foo')
'foo'

字符串索引

在 Python 中,字符串是字符數(shù)據(jù)的有序序列,因此可以通過這種方式進(jìn)行索引??梢酝ㄟ^指定字符串名稱后跟方括號 ( []) 中的數(shù)字來訪問字符串中的各個字符。

Python 中的字符串索引是從零開始的:字符串中的第一個字符具有 index 0,下一個字符具有 index 1,依此類推。最后一個字符的索引將是字符串的長度減1。

>>> s = 'foobar'

# 正索引
>>> s[0]
'f'
>>> s[1]
'o'
>>> s[3]
'b'
>>> len(s)
6
>>> s[len(s)-1]
'r'

# 負(fù)索引
>>> s[-1]
'r'
>>> s[-2]
'a'
>>> len(s)
6
>>> s[-len(s)]
'f'

嘗試超出字符串末尾的索引會導(dǎo)致錯誤。

# 正索引
>>> s[6]
Traceback (most recent call last):
? File "<pyshell#17>", line 1, in <module>
? ? s[6]
IndexError: string index out of range

# 負(fù)索引
>>> s[-7]
Traceback (most recent call last):
? File "<pyshell#26>", line 1, in <module>
? ? s[-7]
IndexError: string index out of range

字符串切片

Python 還允許一種從字符串中提取子字符串的索引語法形式,稱為字符串切片。如果s是字符串,則形式的表達(dá)式返回以 position 開頭 s[m:n] 的部分。

>>> s = 'foobar'
>>> s[2:5]
'oba'

省略第一個索引,則切片從字符串的開頭開始。因此s[:m]和s[0:m]是等價的。

>>> s = 'foobar'

>>> s[:4]
'foob'
>>> s[0:4]
'foob'

省略第二個索引s[n:],則切片從第一個索引延伸到字符串的末尾。

>>> s = 'foobar'

>>> s[2:]
'obar'
>>> s[2:len(s)]
'obar'

對于任何字符串s和任何整數(shù)n( 0 ≤ n ≤ len(s)),s[:n] + s[n:]將等于s。

>>> s = 'foobar'

>>> s[:4] + s[4:]
'foobar'
>>> s[:4] + s[4:] == s
True

省略兩個索引會返回完整的原始字符串。

>>> s = 'foobar'
>>> t = s[:]
>>> id(s)
59598496
>>> id(t)
59598496
>>> s is t
True

字符串切片中的步幅

對于 string ‘foobar’,切片0:6:2從第一個字符開始,到最后一個字符(整個字符串)結(jié)束,并且每隔一個字符被跳過。

1:6:2指定從第二個字符(索引1)開始并以最后一個字符結(jié)束的切片,并且步幅值再次2導(dǎo)致每隔一個字符被跳過。

>>> s = 'foobar'

>>> s[0:6:2]
'foa'

>>> s[1:6:2]
'obr'

第一個和第二個索引可以省略,并分別默認(rèn)為第一個和最后一個字符。

>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::5]
'11111'
>>> s[4::5]
'55555'

也可以指定一個負(fù)的步幅值,Python 會向后遍歷字符串,開始/第一個索引應(yīng)該大于結(jié)束/第二個索引。

>>> s = 'foobar'
>>> s[5:0:-2]
'rbo'

第一個索引默認(rèn)為字符串的末尾,第二個索引默認(rèn)為開頭。

>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::-5]
'55555'

將變量插入字符串

f-strings 提供的格式化功能非常廣泛,后面還有一個關(guān)于格式化輸出的教程。

顯示算術(shù)計算的結(jié)果??梢杂靡粋€簡單的 print() 語句來做到這一點,用逗號分隔數(shù)值和字符串文字。

>>> n = 20
>>> m = 25
>>> prod = n * m
>>> print('The product of', n, 'and', m, 'is', prod)
The product of 20 and 25 is 500

使用 f-string 重鑄,上面的示例看起來更清晰。

>>> n = 20
>>> m = 25
>>> prod = n * m
>>> print(f'The product of {n} and {m} is {prod}')
The product of 20 and 25 is 500

Python 的三種引用機(jī)制中的任何一種都可用于定義 f 字符串。

>>> var = 'Bark'

>>> print(f'A dog says {var}!')
A dog says Bark!
>>> print(f"A dog says {var}!")
A dog says Bark!
>>> print(f'''A dog says {var}!''')
A dog says Bark!

修改字符串

字符串是 Python 認(rèn)為不可變的數(shù)據(jù)類型之一,修改會導(dǎo)致錯誤。

>>> s = 'foobar'
>>> s[3] = 'x'
Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    s[3] = 'x'
TypeError: 'str' object does not support item assignment

可以通過生成具有所需更改的原始字符串的副本來輕松完成所需的操作。

>>> s = s[:3] + 'x' + s[4:]
>>> s
'fooxar'

可以使用內(nèi)置的字符串方法完成修改操作。

>>> s = 'foobar'
>>> s = s.replace('b', 'x')
>>> s
'fooxar'

內(nèi)置字符串方法

Python 程序中的每一項數(shù)據(jù)都是一個對象。

dir會返回一個內(nèi)置方法與屬性列表。

>>> dir('a,b,cdefg')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

方法類似于函數(shù)。方法是與對象緊密關(guān)聯(lián)的一種特殊類型的可調(diào)用過程。像函數(shù)一樣,調(diào)用方法來執(zhí)行不同的任務(wù),但它是在特定對象上調(diào)用的,并且在執(zhí)行期間知道其目標(biāo)對象。

目標(biāo)字符串執(zhí)行大小寫轉(zhuǎn)換應(yīng)用舉例

s.capitalize() 將目標(biāo)字符串大寫

# 返回第一個字符轉(zhuǎn)換為大寫,所有其他字符轉(zhuǎn)換為小寫的副本
>>> s = 'foO BaR BAZ quX'
>>> s.capitalize()
'Foo bar baz qux'
# 非字母字符不變
>>> s = 'foo123#BAR#.'
>>> s.capitalize()
'Foo123#bar#.'

s.lower() 將字母字符轉(zhuǎn)換為小寫

# 返回所有字母字符都轉(zhuǎn)換為小寫的副本
>>> 'FOO Bar 123 baz qUX'.lower()
'foo bar 123 baz qux'

s.swapcase() 交換字母字符的大小寫

# 返回將大寫字母字符轉(zhuǎn)換為小寫字母的副本,s反之亦然
>>> 'FOO Bar 123 baz qUX'.swapcase()
'foo bAR 123 BAZ Qux'

**s.title() 將目標(biāo)字符串轉(zhuǎn)換為 標(biāo)題大小寫 **

# 返回一個副本,s其中每個單詞的第一個字母轉(zhuǎn)換為大寫,其余字母為小寫
>>> 'the sun also rises'.title()
'The Sun Also Rises'

s.upper() 將字母字符轉(zhuǎn)換為大寫

# 返回所有字母字符都轉(zhuǎn)換為大寫的副本
>>> 'FOO Bar 123 baz qUX'.upper()
'FOO BAR 123 BAZ QUX'

查找和替換方法應(yīng)用舉例

s.count(<sub>,[<start>,<end>]) 計算目標(biāo)字符串中子字符串的出現(xiàn)次數(shù)

# 返回字符串中非重疊出現(xiàn)的<sub>次數(shù)
>>> 'foo goo moo'.count('oo')
3
# 指定切片位置
>>> 'foo goo moo'.count('oo', 0, 8)
2

s.endswith(<suffix>,[<start>,<end>]) 確定目標(biāo)字符串是否以給定的子字符串結(jié)尾

# s.endswith(<suffix>)如果s以指定的結(jié)尾則返回True,否則返回False
>>> 'foobar'.endswith('bar')
True
>>> 'foobar'.endswith('baz')
False
# 指定切片位置
>>> 'foobar'.endswith('oob', 0, 4)
True
>>> 'foobar'.endswith('oob', 2, 4)
False

s.find(<sub>,[<start>,<end>]) 在目標(biāo)字符串中搜索給定的子字符串

# 返回找到子字符串s.find(<sub>)的索引
>>> 'foo bar foo baz foo qux'.find('foo')
0
# 如果未找到指定的子字符串,則此方法返回-1
>>> 'foo bar foo baz foo qux'.find('grault')
-1
# 指定切片位置
>>> 'foo bar foo baz foo qux'.find('foo', 4)
8
>>> 'foo bar foo baz foo qux'.find('foo', 4, 7)
-1

s.index(<sub>,[<start>,<end>]) 在目標(biāo)字符串中搜索給定的子字符串

# 和find相同,但是未找到會引發(fā)異常
>>> 'foo bar foo baz foo qux'.index('grault')
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    'foo bar foo baz foo qux'.index('grault')
ValueError: substring not found

s.rfind(<sub>,[<start>,<end>]) 從末尾開始搜索給定子字符串的目標(biāo)字符串

# 返回找到子字符串的最高索引
>>> 'foo bar foo baz foo qux'.rfind('foo')
16
# 未找到子字符串則返回-1
>>> 'foo bar foo baz foo qux'.rfind('grault')
-1
# 指定切片位置
>>> 'foo bar foo baz foo qux'.rfind('foo', 0, 14)
8
>>> 'foo bar foo baz foo qux'.rfind('foo', 10, 14)
-1

s.rindex(<sub>,[<start>,<end>]) 從末尾開始搜索給定子字符串的目標(biāo)字符串

# 和rfind相同,但是未找到會引發(fā)異常
>>> 'foo bar foo baz foo qux'.rindex('grault')
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    'foo bar foo baz foo qux'.rindex('grault')
ValueError: substring not found

s.startswith(<prefix>,[<start>,<end>]) 確定目標(biāo)字符串是否以給定的子字符串開頭

# 返回判斷是否以字符串<suffix>開頭的結(jié)果
>>> 'foobar'.startswith('foo')
True
>>> 'foobar'.startswith('bar')
False
# 指定切片位置
>>> 'foobar'.startswith('bar', 3)
True
>>> 'foobar'.startswith('bar', 3, 2)
False

字符分類方法應(yīng)用舉例

s.isalnum() 確定目標(biāo)字符串是否由字母數(shù)字字符組成

# 如果s為非空且其所有字符都是字母數(shù)字(字母或數(shù)字)返回True
>>> 'abc123'.isalnum()
True
>>> 'abc$123'.isalnum()
False
>>> ''.isalnum()
False

s.isalpha() 確定目標(biāo)字符串是否由字母字符組成

# s為非空且其所有字符都是字母則返回True
>>> 'ABCabc'.isalpha()
True
>>> 'abc123'.isalpha()
False

s.isdigit() 確定目標(biāo)字符串是否由數(shù)字字符組成

# 如果為非空且其所有字符都是數(shù)字則返回True
>>> '123'.isdigit()
True
>>> '123abc'.isdigit()
False

s.isidentifier() 確定目標(biāo)字符串是否是有效的 Python 標(biāo)識符

# 有效的 Python 標(biāo)識符返回True
>>> 'foo32'.isidentifier()
True
>>> '32foo'.isidentifier()
False
>>> 'foo$32'.isidentifier()
False

s.islower() 確定目標(biāo)字符串的字母字符是否為小寫

# 非空并且它包含的所有字母字符都是小寫則返回True
>>> 'abc'.islower()
True
>>> 'abc1$d'.islower()
True
>>> 'Abc1$D'.islower()
False

s.isprintable() 確定目標(biāo)字符串是否完全由可打印字符組成

# 為空或包含的所有字母字符都是可打印的則返回True
>>> 'a\tb'.isprintable()
False
>>> 'a b'.isprintable()
True
>>> ''.isprintable()
True
>>> 'a\nb'.isprintable()
False

s.isspace() 確定目標(biāo)字符串是否由空白字符組成

# 為非空且所有字符都是空白字符則返回True
>>> ' \t \n '.isspace()
True
>>> '   a   '.isspace()
False
#  ASCII 字符可以作為空格
>>> '\f\u2005\r'.isspace()
True

s.istitle() 確定目標(biāo)字符串是否為標(biāo)題大小寫

# 則返回每個單詞的第一個字母字符為大寫,并且每個單詞中的所有其他字母字符均為小寫為True
>>> 'This Is A Title'.istitle()
True
>>> 'This is a title'.istitle()
False
>>> 'Give Me The #$#@ Ball!'.istitle()
True

s.isupper() 確定目標(biāo)字符串的字母字符是否為大寫

# 為非空并且它包含的所有字母字符都是大寫則返回True
>>> 'ABC'.isupper()
True
>>> 'ABC1$D'.isupper()
True
>>> 'Abc1$D'.isupper()
False

字符串格式方法應(yīng)用舉例

s.center(<width>,[<fill>]) 使字段中的字符串居中

# 返回一個由以寬度為中心的字段組成的字符串<width>
>>> 'foo'.center(10)
'   foo    '
# 指定填充字符
>>> 'bar'.center(10, '-')
'---bar----'
# 字符長度小于指定返回原字符
>>> 'foo'.center(2)
'foo'

s.expandtabs(tabsize=8) 展開字符串中的制表符

# 將每個制表符 ( '\t') 替換為空格
>>> 'a\tb\tc'.expandtabs()
'a       b       c'
>>> 'aaa\tbbb\tc'.expandtabs()
'aaa     bbb     c'
# tabsize指定備用制表位列
>>> 'a\tb\tc'.expandtabs(4)
'a   b   c'
>>> 'aaa\tbbb\tc'.expandtabs(tabsize=4)
'aaa bbb c'

s.ljust(,[<fill>]) 左對齊字段中的字符串

# 返回一個由寬度為左對齊的字段組成的字符串<width>
>>> 'foo'.ljust(10)
'foo       '
# 指定填充字符
>>> 'foo'.ljust(10, '-')
'foo-------'
# 字符長度小于指定返回原字符
>>> 'foo'.ljust(2)
'foo'

s.lstrip([<chars>]) 修剪字符串中的前導(dǎo)字符

# 返回從左端刪除任何空白字符的副本
>>> '   foo bar baz   '.lstrip()
'foo bar baz   '
>>> '\t\nfoo\t\nbar\t\nbaz'.lstrip()
'foo\t\nbar\t\nbaz'

s.replace(<old>, <new>[, <count>]) 替換字符串中出現(xiàn)的子字符串

# 返回所有出現(xiàn)的子字符串替換為s.replace(<old>, <new>)的副本
>>> 'foo bar foo baz foo qux'.replace('foo', 'grault')
'grault bar grault baz grault qux'
# <count>參數(shù)指定替換數(shù)
>>> 'foo bar foo baz foo qux'.replace('foo', 'grault', 2)
'grault bar grault baz foo qux'

s.rjust(<width>, [<fill>]) 右對齊字段中的字符串

# 返回一個由寬度字段右對齊組成的字符串<width>
>>> 'foo'.rjust(10)
'       foo'
# 指定填充字符
>>> 'foo'.rjust(10, '-')
'-------foo'
# 字符長度小于指定返回原字符
>>> 'foo'.rjust(2)
'foo'

s.rstrip([<chars>]) 修剪字符串中的尾隨字符

# 返回從右端刪除任何空白字符的副本
>>> '   foo bar baz   '.rstrip()
'   foo bar baz'
>>> 'foo\t\nbar\t\nbaz\t\n'.rstrip()
'foo\t\nbar\t\nbaz'
# 指定刪除字符集
>>> 'foo.$$$;'.rstrip(';$.')
'foo'

s.strip([<chars>]) 從字符串的左右兩端去除字符

# 同時調(diào)用s.lstrip()和s.rstrip()
>>> s = '   foo bar baz\t\t\t'
>>> s = s.lstrip()
>>> s = s.rstrip()
>>> s
'foo bar baz'
# 指定刪除字符集
>>> 'www.realpython.com'.strip('w.moc')
'realpython'

s.zfill(<width>) 用零填充左側(cè)的字符串

# 將左填充'0'字符的副本返回到指定的<width>
>>> '42'.zfill(5)
'00042'
# 如果包含符號仍保留
>>> '+42'.zfill(8)
'+0000042'
>>> '-42'.zfill(8)
'-0000042'
# 字符長度小于指定返回原字符
>>> '-42'.zfill(3)
'-42'

順序集合 iterables 字符串和列表之間的轉(zhuǎn)換方法應(yīng)用舉例

s.join(<iterable>) 連接來自可迭代對象的字符串

# 返回由分隔的對象連接得到的字符串
>>> ', '.join(['foo', 'bar', 'baz', 'qux'])
'foo, bar, baz, qux'
# 字符串的操作
>>> list('corge')
['c', 'o', 'r', 'g', 'e']
>>> ':'.join('corge')
'c:o:r:g:e'
# list中的數(shù)據(jù)必須是字符串
>>> '---'.join(['foo', 23, 'bar'])
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    '---'.join(['foo', 23, 'bar'])
TypeError: sequence item 1: expected str instance, int found
>>> '---'.join(['foo', str(23), 'bar'])
'foo---23---bar'

s.partition(<sep>) 根據(jù)分隔符劃分字符串

# 返回值是一個由三部分組成的元組:<sep>前、<sep>本身、<sep>后
>>> 'foo.bar'.partition('.')
('foo', '.', 'bar')
>>> 'foo@@bar@@baz'.partition('@@')
('foo', '@@', 'bar@@baz')
# 如果未找到則返回2個空字符
>>> 'foo.bar'.partition('@@')
('foo.bar', '', '')

s.rpartition(<sep>) 根據(jù)分隔符劃分字符串

# 與s.partition(<sep>)相同,用于指定最后一次拆分符
>>> 'foo@@bar@@baz'.partition('@@')
('foo', '@@', 'bar@@baz')
>>> 'foo@@bar@@baz'.rpartition('@@')
('foo@@bar', '@@', 'baz')

s.rsplit(sep=None, maxsplit=-1) 將字符串拆分為子字符串列表

# 返回拆分為由任何空格序列分隔的子字符串,并將子字符串作為列表
>>> 'foo bar baz qux'.rsplit()
['foo', 'bar', 'baz', 'qux']
>>> 'foo\n\tbar   baz\r\fqux'.rsplit()
['foo', 'bar', 'baz', 'qux']
# 指定拆分符
>>> 'foo.bar.baz.qux'.rsplit(sep='.')
['foo', 'bar', 'baz', 'qux']
# 指定最多拆分次數(shù)
>>> 'www.realpython.com'.rsplit(sep='.', maxsplit=1)
['www.realpython', 'com']
>>> 'www.realpython.com'.rsplit(sep='.', maxsplit=-1)
['www', 'realpython', 'com']
>>> 'www.realpython.com'.rsplit(sep='.')
['www', 'realpython', 'com']

s.split(sep=None, maxsplit=-1) 將字符串拆分為子字符串列表

# 與s.rsplit()一樣,指定<maxsplit>則從左端而不是右端計算拆分
>>> 'www.realpython.com'.split('.', maxsplit=1)
['www', 'realpython.com']
>>> 'www.realpython.com'.rsplit('.', maxsplit=1)
['www.realpython', 'com']

s.splitlines([<keepends>]) 在行邊界處斷開字符串

# 返回?fù)Q行符切分的列表,其中包含\n、\r、\r\n、\v or \x0b、\f or \x0c、\x1c、\x1d、\x1e、\x85、\u2028、\u2029
>>> 'foo\nbar\r\nbaz\fqux\u2028quux'.splitlines()
['foo', 'bar', 'baz', 'qux', 'quux']
# 同時存在多個空白行
>>> 'foo\f\f\fbar'.splitlines()
['foo', '', '', 'bar']
# 也可以保留行邊界符號
>>> 'foo\nbar\nbaz\nqux'.splitlines(True)
['foo\n', 'bar\n', 'baz\n', 'qux']
>>> 'foo\nbar\nbaz\nqux'.splitlines(1)
['foo\n', 'bar\n', 'baz\n', 'qux']

bytes對象

對象是操作二進(jìn)制數(shù)據(jù)的bytes核心內(nèi)置類型之一。bytes對象是不可變的單字節(jié)值序列。

定義文字bytes對象

文字的bytes定義方式與添加’b’前綴的字符串文字相同。

>>> b = b'foo bar baz'
>>> b
b'foo bar baz'
>>> type(b)
<class 'bytes'>

可以使用任何單引號、雙引號或三引號機(jī)制。

>>> b'Contains embedded "double" quotes'
b'Contains embedded "double" quotes'

>>> b"Contains embedded 'single' quotes"
b"Contains embedded 'single' quotes"

>>> b'''Contains embedded "double" and 'single' quotes'''
b'Contains embedded "double" and \'single\' quotes'

>>> b"""Contains embedded "double" and 'single' quotes"""
b'Contains embedded "double" and \'single\' quotes'

'r’前綴可以用在文字上以禁用轉(zhuǎn)義序列的bytes處理。

>>> b = rb'foo\xddbar'
>>> b
b'foo\\xddbar'
>>> b[3]
92
>>> chr(92)
'\\'

bytes使用內(nèi)置bytes()函數(shù)定義對象

bytes()函數(shù)還創(chuàng)建一個bytes對象。返回什么樣的bytes對象取決于傳遞給函數(shù)的參數(shù)。

bytes(<s>, <encoding>) bytes從字符串創(chuàng)建對象

# 根據(jù)指定的使用將字符串轉(zhuǎn)換<s>為bytes對象
>>> b = bytes('foo.bar', 'utf8')
>>> b
b'foo.bar'
>>> type(b)
<class 'bytes'>

bytes(<size>) 創(chuàng)建一個bytes由 null ( 0x00) 字節(jié)組成的對象

# 定義bytes指定的對象<size>必須是一個正整數(shù)。
>>> b = bytes(8)
>>> b
b'\x00\x00\x00\x00\x00\x00\x00\x00'
>>> type(b)
<class 'bytes'>

bytes() bytes從可迭代對象創(chuàng)建對象

# 生成的整數(shù)序列中定義一個對象<iterable> n0 ≤ n ≤ 255
>>> b = bytes([100, 102, 104, 106, 108])
>>> b
b'dfhjl'
>>> type(b)
<class 'bytes'>
>>> b[2]
104

bytes對象操作,操作參考字符串。

運算符 in 和 not in

>>> b = b'abcde'
>>> b'cd' in b
True
>>> b'foo' not in b
True

*連接 ( +) 和復(fù)制 ( ) 運算符

>>> b = b'abcde'
>>> b + b'fghi'
b'abcdefghi'
>>> b * 3
b'abcdeabcdeabcde'

索引和切片

>>> b = b'abcde'
>>> b[2]
99
>>> b[1:3]
b'bc'

內(nèi)置功能

>>> b = b'foo,bar,foo,baz,foo,qux'
>>> len(b)
23
>>> min(b)
44
>>> max(b)
122
>>> b = b'foo,bar,foo,baz,foo,qux'
>>> b.count(b'foo')
3
>>> b.endswith(b'qux')
True
>>> b.find(b'baz')
12
>>> b.split(sep=b',')
[b'foo', b'bar', b'foo', b'baz', b'foo', b'qux']
>>> b.center(30, b'-')
b'---foo,bar,foo,baz,foo,qux----'
>>> b[2:3]
b'o'
>>> list(b)
[102, 111, 111, 44, 98, 97, 114, 44, 102, 111, 111, 44, 98, 97, 122, 44, 102, 111, 111, 44, 113, 117, 120]

bytes.fromhex(<s>) 返回bytes從一串十六進(jìn)制值構(gòu)造的對象

# 返回bytes將每對十六進(jìn)制數(shù)字轉(zhuǎn)換<s>為相應(yīng)字節(jié)值的對象
>>> b = bytes.fromhex(' aa 68 4682cc ')
>>> b
b'\xaahF\x82\xcc'
>>> list(b)
[170, 104, 70, 130, 204]

b.hex() bytes從對象返回一串十六進(jìn)制值

# 將bytes對象b轉(zhuǎn)換為十六進(jìn)制數(shù)字對字符串的結(jié)果,與.fromhex()相反
>>> b = bytes.fromhex(' aa 68 4682cc ')
>>> b
b'\xaahF\x82\xcc'

>>> b.hex()
'aa684682cc'
>>> type(b.hex())
<class 'str'>

bytearray對象,Python 支持的另一種二進(jìn)制序列類型

bytearray始終使用內(nèi)置函數(shù)創(chuàng)建對象bytearray()

>>> ba = bytearray('foo.bar.baz', 'UTF-8')
>>> ba
bytearray(b'foo.bar.baz')
>>> bytearray(6)
bytearray(b'\x00\x00\x00\x00\x00\x00')
>>> bytearray([100, 102, 104, 106, 108])
bytearray(b'dfhjl')

bytearray對象是可變的,可以使用索引和切片修改對象的內(nèi)容

>>> ba = bytearray('foo.bar.baz', 'UTF-8')
>>> ba
bytearray(b'foo.bar.baz')
>>> ba[5] = 0xee
>>> ba
bytearray(b'foo.b\xeer.baz')
>>> ba[8:11] = b'qux'
>>> ba
bytearray(b'foo.b\xeer.qux')

bytearray對象也可以直接從對象構(gòu)造bytes

>>> ba = bytearray(b'foo')
>>> ba
bytearray(b'foo')

以上就是Python必備技巧之字符數(shù)據(jù)操作詳解的詳細(xì)內(nèi)容,更多關(guān)于Python字符數(shù)據(jù)操作的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python進(jìn)階教程之文本文件的讀取和寫入

    python進(jìn)階教程之文本文件的讀取和寫入

    這篇文章主要介紹了python進(jìn)階教程之文本文件的讀取和寫入,本文講解的是最基本的文件讀取和寫入功能,需要的朋友可以參考下
    2014-08-08
  • 總結(jié)歸納python os庫常用方法

    總結(jié)歸納python os庫常用方法

    這篇文章主要為大家介紹了python os庫常用方法的總結(jié)歸納,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-03-03
  • Python中的 enum 模塊源碼詳析

    Python中的 enum 模塊源碼詳析

    這篇文章主要給大家介紹了關(guān)于Python中 enum 模塊的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-01-01
  • Python 私有屬性和私有方法應(yīng)用場景分析

    Python 私有屬性和私有方法應(yīng)用場景分析

    這篇文章主要介紹了Python 私有屬性和私有方法應(yīng)用場景分析,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-06-06
  • 由Python編寫的MySQL管理工具代碼實例

    由Python編寫的MySQL管理工具代碼實例

    這篇文章主要介紹了由Python編寫的MySQL管理工具,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • 用實例解釋Python中的繼承和多態(tài)的概念

    用實例解釋Python中的繼承和多態(tài)的概念

    這篇文章主要介紹了用實例解釋Python中的繼承和多態(tài)的概念,繼承和多臺是學(xué)習(xí)每一門面對對象的編程語言時都必須掌握的重要知識,需要的朋友可以參考下
    2015-04-04
  • django連接數(shù)據(jù)庫獲取數(shù)據(jù)的簡單步驟記錄

    django連接數(shù)據(jù)庫獲取數(shù)據(jù)的簡單步驟記錄

    數(shù)據(jù)庫中各種表結(jié)構(gòu)已經(jīng)創(chuàng)建好了,甚至連數(shù)據(jù)都有了,此時我要用Django管理這個數(shù)據(jù)庫,下面這篇文章主要給大家介紹了關(guān)于django連接數(shù)據(jù)庫獲取數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下
    2022-07-07
  • PyQt5?python?數(shù)據(jù)庫?表格動態(tài)增刪改詳情

    PyQt5?python?數(shù)據(jù)庫?表格動態(tài)增刪改詳情

    這篇文章主要介紹了PyQt5?python?數(shù)據(jù)庫?表格動態(tài)增刪改詳情,首先手動連接數(shù)據(jù)庫與下一個的程序連接數(shù)據(jù)庫是獨立的2個部分,下面來看看文章的詳細(xì)介紹
    2022-01-01
  • Python如何進(jìn)行時間處理

    Python如何進(jìn)行時間處理

    這篇文章主要介紹了Python如何進(jìn)行時間處理,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-08-08
  • 接口自動化多層嵌套json數(shù)據(jù)處理代碼實例

    接口自動化多層嵌套json數(shù)據(jù)處理代碼實例

    這篇文章主要介紹了接口自動化多層嵌套json數(shù)據(jù)處理代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-11-11

最新評論