溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python字符數(shù)據(jù)操作的示例分析

發(fā)布時(shí)間:2022-03-23 14:07:40 來(lái)源:億速云 閱讀:141 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)Python字符數(shù)據(jù)操作的示例分析,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

字符串操作

Python字符數(shù)據(jù)操作的示例分析

字符串 + 運(yùn)算符

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

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

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

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

字符串 * 運(yùn)算符

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

>>> s = 'f.'

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

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

>>> 'f' * -8
''

字符串 in 運(yùn)算符

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

>>> s = 'foo'

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

用于相反的處理操作 not in 運(yùn)算符。

>>> '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()返回字符串的長(zhǎng)度
str()返回對(duì)象的字符串表示形式
# ord(c)
# 計(jì)算機(jī)將所有信息存儲(chǔ)為數(shù)字,使用了一種將每個(gè)字符映射到其代表數(shù)字的轉(zhuǎn)換方案
# 常用方案稱為ASCII。它涵蓋了您可能最習(xí)慣使用的常見拉丁字符
# ord(c)返回 character 的 ASCII 值
>>> ord('a')
97
>>> ord('#')
35

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


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

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

字符串索引

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

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

Python字符數(shù)據(jù)操作的示例分析

>>> 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'

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

# 正索引
>>> 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 還允許一種從字符串中提取子字符串的索引語(yǔ)法形式,稱為字符串切片。如果s是字符串,則形式的表達(dá)式返回以 position 開頭 s[m:n] 的部分。

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

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

>>> s = 'foobar'

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

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

>>> s = 'foobar'

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

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

>>> s = 'foobar'

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

省略兩個(gè)索引會(huì)返回完整的原始字符串。

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

字符串切片中的步幅

對(duì)于 string &lsquo;foobar&rsquo;,切片0:6:2從第一個(gè)字符開始,到最后一個(gè)字符(整個(gè)字符串)結(jié)束,并且每隔一個(gè)字符被跳過(guò)。

Python字符數(shù)據(jù)操作的示例分析

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

Python字符數(shù)據(jù)操作的示例分析

>>> s = 'foobar'

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

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

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

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

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

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

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

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

將變量插入字符串

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

顯示算術(shù)計(jì)算的結(jié)果??梢杂靡粋€(gè)簡(jiǎn)單的 print() 語(yǔ)句來(lái)做到這一點(diǎn),用逗號(hào)分隔數(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 重鑄,上面的示例看起來(lái)更清晰。

>>> 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ù)類型之一,修改會(huì)導(dǎo)致錯(cuò)誤。

>>> 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

可以通過(guò)生成具有所需更改的原始字符串的副本來(lái)輕松完成所需的操作。

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

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

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

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

Python 程序中的每一項(xiàng)數(shù)據(jù)都是一個(gè)對(duì)象。

dir會(huì)返回一個(gè)內(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ù)。方法是與對(duì)象緊密關(guān)聯(lián)的一種特殊類型的可調(diào)用過(guò)程。像函數(shù)一樣,調(diào)用方法來(lái)執(zhí)行不同的任務(wù),但它是在特定對(duì)象上調(diào)用的,并且在執(zhí)行期間知道其目標(biāo)對(duì)象。

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

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

# 返回第一個(gè)字符轉(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)題大小寫 **

# 返回一個(gè)副本,s其中每個(gè)單詞的第一個(gè)字母轉(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>]) 計(jì)算目標(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相同,但是未找到會(huì)引發(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相同,但是未找到會(huì)引發(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)識(shí)符

# 有效的 Python 標(biāo)識(shí)符返回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)題大小寫

# 則返回每個(gè)單詞的第一個(gè)字母字符為大寫,并且每個(gè)單詞中的所有其他字母字符均為小寫為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>]) 使字段中的字符串居中

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

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

# 將每個(gè)制表符 ( '\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>]) 左對(duì)齊字段中的字符串

# 返回一個(gè)由寬度為左對(duì)齊的字段組成的字符串<width>
>>> 'foo'.ljust(10)
'foo       '
# 指定填充字符
>>> 'foo'.ljust(10, '-')
'foo-------'
# 字符長(zhǎng)度小于指定返回原字符
>>> '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>]) 右對(duì)齊字段中的字符串

# 返回一個(gè)由寬度字段右對(duì)齊組成的字符串<width>
>>> 'foo'.rjust(10)
'       foo'
# 指定填充字符
>>> 'foo'.rjust(10, '-')
'-------foo'
# 字符長(zhǎng)度小于指定返回原字符
>>> '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>]) 從字符串的左右兩端去除字符

# 同時(shí)調(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'
# 如果包含符號(hào)仍保留
>>> '+42'.zfill(8)
'+0000042'
>>> '-42'.zfill(8)
'-0000042'
# 字符長(zhǎng)度小于指定返回原字符
>>> '-42'.zfill(3)
'-42'

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

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

# 返回由分隔的對(duì)象連接得到的字符串
>>> ', '.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ù)分隔符劃分字符串

# 返回值是一個(gè)由三部分組成的元組:<sep>前、<sep>本身、<sep>后
>>> 'foo.bar'.partition('.')
('foo', '.', 'bar')
>>> 'foo@@bar@@baz'.partition('@@')
('foo', '@@', 'bar@@baz')
# 如果未找到則返回2個(gè)空字符
>>> '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>則從左端而不是右端計(jì)算拆分
>>> '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']
# 同時(shí)存在多個(gè)空白行
>>> 'foo\f\f\fbar'.splitlines()
['foo', '', '', 'bar']
# 也可以保留行邊界符號(hào)
>>> '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對(duì)象

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

Python字符數(shù)據(jù)操作的示例分析

定義文字bytes對(duì)象

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

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

可以使用任何單引號(hào)、雙引號(hào)或三引號(hào)機(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&rsquo;前綴可以用在文字上以禁用轉(zhuǎn)義序列的bytes處理。

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

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

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

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

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

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

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

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

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

bytes對(duì)象操作,操作參考字符串。

運(yùn)算符 in 和 not in

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

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

>>> 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)造的對(duì)象

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

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

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

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

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

bytearray始終使用內(nèi)置函數(shù)創(chuàng)建對(duì)象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對(duì)象是可變的,可以使用索引和切片修改對(duì)象的內(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對(duì)象也可以直接從對(duì)象構(gòu)造bytes

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

關(guān)于“Python字符數(shù)據(jù)操作的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI