4.字符串String

目錄
0.字符串介紹
1.字符串定義和初始化
2.字符串元素訪問(wèn)
3.字符串連接
4.字符串分割
5.字符串修改
6.字符串判斷
7.字符串格式化

0.字符串介紹

一個(gè)個(gè)字符組成的有序的序列,是字符的集合
使用單引號(hào)、雙引號(hào)鲁驶、三引號(hào)引住的字符序列
字符串是不可變對(duì)象
從Python3開(kāi)始膀跌,字符串就是Unicode類型

1.字符串定義和初始化

r和R前綴會(huì)使字符串中的轉(zhuǎn)義字符無(wú)效

>>> s1 = 'string'
>>> s2 = "string"
>>> print(s1,s2)
string string
>>> s3 = '''this is a "String" '''
>>> print(s3)
this is a "String" 
>>> s4 = 'hello \n magedu.com'
>>> print(s4)
hello 
 magedu.com
>>> s5 = r"hello \n magedu.com"
>>> print(s5)
hello \n magedu.com
>>> s7 = R"c:\windows\nt"
>>> print(s7)
c:\windows\nt
>>> s8 = 'c:\windows\\nt'
>>> print(s8)
c:\windows\nt
>>> sql = """select * from user where name='tom'"""
>>> sql
"select * from user where name='tom'"
>>> print(sql)
select * from user where name='tom'

2.字符串元素訪問(wèn)

2.1 下標(biāo)訪問(wèn)

下標(biāo)訪問(wèn)

>>> str1 = "abcdefg"
>>> str1[1]
'b'

循環(huán)迭代

>>> for c in str1:
...     print(c,type(c))
... 
a <class 'str'>
...
g <class 'str'>
>>> lst = list(str1)
>>> lst
['a', 'b', 'c', 'd', 'e', 'f', 'g']
2.2 字符串查找 --> find方法

find(sub[,start[,end]]) -> int
在指定的區(qū)間[start,stop)踢涌,從左至右琼腔,查找子串sub抡诞。
找到返回索引适刀,沒(méi)找到返回-1

>>> s1 = "I am stone stone stone stone life"
>>> s1.find("stone",5)
5
>>> s1.find("stone",6,13)
-1
>>> s1.find("stone",10)
11
>>> s1.find("stone",10,15)
-1
>>> s1.find("stone",-20,-1)
17

rfind(sub[,start[,end]]) -> int
在指定的區(qū)間[start,stop)秤朗,從右至左,查找子串sub笔喉。
找到返回索引取视,沒(méi)找到返回-1

>>> s1 = "I am stone stone stone stone life"
>>> s1.rfind("stone",-20,-1)
23
>>> s1.rfind("stone",10,15)
-1
>>> s1.rfind("stone",10)
23
2.3 字符串查找 --> index方法

index(sub[,start[,end]]) -> int
在指定的區(qū)間[start,stop)硝皂,從左至右,查找子串sub作谭。
找到返回索引稽物,沒(méi)找到返回ValueError

>>> s1 = "I am stone stone stone stone life"
>>> s1.index('stone')
5
>>> s1.index('stone',6,13)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s1.index('stone',6,20)
11

rindex(sub[,start[,end]]) -> int
在指定的區(qū)間[start,stop),從右至左折欠,查找子串sub贝或。
找到返回索引,沒(méi)找到返回ValueError

>>> s1 = "I am stone stone stone stone life"
>>> s1.rindex('stone',-10,-1)
23
>>> s1.rindex('stone',-2,-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
2.4 返回字串個(gè)數(shù) --> count方法

count(sub[,start[,end]]) -> int
在指定的區(qū)間[start,end)锐秦,從左至右咪奖,統(tǒng)計(jì)字串sub出現(xiàn)的次數(shù)

>>> s1 = "I am stone stone stone stone life"
>>> s1
'I am stone stone stone stone life'
>>> s1.count("stone")
4
>>> s1.count("a")
1
2.5 返回字符串長(zhǎng)度 --> len(str)
>>> s1 = "I am stone stone stone stone life"
>>> len(s1)
33

3.字符串連接

3.1 jion連接 -> "string".join(iterable) -> str

將可迭代對(duì)象連接起來(lái),使用string作為分隔符
可迭代對(duì)象本身元素必須是字符串
返回一個(gè)新字符串

>>> lst1 = [1,2,3]    #列表中元素不是字符串類型酱床,無(wú)法拼接
>>> "**".join(lst1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
>>> lst2 = ['1','2','3']
>>> "**".join(lst2)
'1**2**3'
>>> "  ".join(lst2)
'1  2  3'
>>> "\n".join(lst2)
'1\n2\n3'
>>> print("\n".join(lst2))
1
2
3
>>> print("\\n".join(lst2))
1\n2\n3
>>> lst3 = ['1',['a','b'],'3']
>>> "**".join(lst3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 1: expected str instance, list found
3.2 “+”號(hào)連接

將2個(gè)字符串連接在一起
返回一個(gè)新字符串

>>> s1 = 'abc'
>>> s2 = '1234'
>>> s1 + s2
'abc1234

4.字符串分割

4.1 split系 -> 將字符串按照分隔符分割成若干字符串羊赵,并返回列表

split(sep=None,maxsplit=-1) -> list of ranges
從左至右
sep指定分割字符串,缺省的情況下空白字符串作為分隔符
maxsplit指定分割的次數(shù)扇谣,-1表示遍歷整個(gè)字符串

>>> s1 = "I'm \ta good stone"
>>> s1
"I'm \ta good stone"
>>> s1.split()
["I'm", 'a', 'good', 'stone']
>>> s1.split('s')
["I'm \ta good ", 'tone']
>>> s1.split('good')
["I'm \ta ", ' stone']
>>> s1.split(' ',maxsplit=-1)
["I'm", '\ta', 'good', 'stone']
>>> s1.split(' ',maxsplit=1)
["I'm", '\ta good stone']
>>> s1.split(' ',maxsplit=2)
["I'm", '\ta', 'good stone']

rsplit(sep=None,maxsplit=-1) -> list of ranges
從右至左
sep指定分割字符串昧捷,缺省的情況下空白字符串作為分隔符
maxsplit指定分割的次數(shù),-1表示遍歷整個(gè)字符串

>>> s1
"I'm \ta good stone"
>>> s1.rsplit()
["I'm", 'a', 'good', 'stone']
>>> s1.rsplit('good')
["I'm \ta ", ' stone']
>>> s1.split(' ',maxsplit=1)
["I'm", '\ta good stone']
>>> s1.rsplit(' ',maxsplit=1)
["I'm \ta good", 'stone']

splitlines([keepends]) -> list of strings
按照行來(lái)切分字符串
keepends指的是是否保留行分隔符
行分隔符包括\n,\r\n,\r等

>>> 'abc\n\nde fg\rkl\r\n'.splitlines()
['abc', '', 'de fg', 'kl']
>>> 'abc\n\nde fg\rkl\r\n'.splitlines(True)
['abc\n', '\n', 'de fg\r', 'kl\r\n']
>>> s1 = '''I'm a good stone
... You are . '''
>>> s1
"I'm a good stone\nYou are . "
>>> print(s1.splitlines())
["I'm a good stone", 'You are . ']
>>> print(s1.splitlines(True))
["I'm a good stone\n", 'You are . ']

Note:第一個(gè)\n和第二個(gè)\n雖然沒(méi)有字符罐寨,但是分隔的時(shí)候會(huì)產(chǎn)生一個(gè)空元素靡挥,同時(shí)\n結(jié)尾時(shí),不會(huì)再有新的元素鸯绿,但是如果不是連續(xù)兩個(gè)\n一起時(shí)跋破,則不會(huì)有空元素產(chǎn)生

4.2 partition系 -> 將字符串按照分隔符分隔成2段,返回這2段和分隔符的元組

partition(sep) -> (head,sep,tail)
從左至右楞慈,遇到分隔符就把字符串分割成兩部分幔烛,返回頭,分隔符囊蓝,尾三部分的三元組饿悬;
如果沒(méi)有找到分隔符,就返回頭聚霜、2個(gè)空元素的三元組

sep分割字符串狡恬,必須指定

>>> s1 = "I'm \ta good stone"
>>> s1
"I'm \ta good stone"
>>> s1.partition('s')
("I'm \ta good ", 's', 'tone')
>>> s1.partition('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: empty separator
>>> s1.partition('abc')
("I'm \ta good stone", '', '')

rpartition(sep) -> (head,sep,tail)
從右至左,遇到分隔符就把字符串分割成兩部分蝎宇,返回頭弟劲,分隔符,尾三部分的三元組姥芥;
如果沒(méi)有找到分隔符兔乞,就返回頭、2個(gè)空元素的三元組

>>> s1.rpartition('abc')
('', '', "I'm \ta good stone")
>>> s1.rpartition('s')
("I'm \ta good ", 's', 'tone')
>>> s1.rpartition()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: rpartition() takes exactly one argument (0 given)

5.字符串修改

5.1 replace(old,new[,count]) -> str

字符串中找到匹配替換為新子串,返回新字符串
count表示替換幾次庸追,不指定就是全部替換

>>> 'www.stone.com'.replace('w','s')
'sss.stone.com'
>>> 'www.stone.com'.replace('w','s',1)
'sww.stone.com'
>>> 'www.stone.com'.replace('www','s',1)
's.stone.com'
5.2 strip([chars]) -> str

從字符串兩端去除指定的字符集chars中的所有字符
如果chars沒(méi)有指定霍骄,去除兩端的空白字符

>>> s1 = "\r \n \t Hello world\n \t"
>>> s1
'\r \n \t Hello world\n \t'
>>> print(s1)
 
     Hello world
    
>>> s1.strip()
'Hello world'
>>> s1
'\r \n \t Hello world\n \t'
>>> s2 = " I am very very very good "
>>> s2
' I am very very very good '
>>> s2.strip('Id')
' I am very very very good '
>>> s2.strip('Id ')
'am very very very goo'

lstrip([chars]) -> str 從左開(kāi)始
rstrip([chars]) -> str 從右開(kāi)始

>>> s1 = "\r \n \t Hello world\n \t"
>>> s1.lstrip()
'Hello world\n \t'
>>> s1.rstrip()
'\r \n \t Hello world'

6.字符串判斷

6.1 endswith && startswith

endswith(suffix[,start[,end]]) -> bool
在指定的區(qū)間[start,end),字符串是否是suffix結(jié)尾

>>> s2 = 'I am very very very good'
>>> s2.startswith('very')
False
>>> s2.startswith('very',5)
True
>>> s2.startswith('very',5,9)
True
>>> s2.startswith('very',5,10)
True
>>> s2.startswith('very',5,8)

startswith(prefix[,start[,end]]) -> bool
在指定的區(qū)間[start,end)淡溯,字符串是否是prefix開(kāi)頭

>>> s2 = 'I am very very very good'
>>> s2.endswith('good')
True
>>> s2.endswith('ood')
True
>>> s2.endswith('good',5,100)
True
>>> s2.endswith('good',5,-1)
False
6.2 字符串判斷is系列

isalpha() 是否是字母
isidentifier() 是不是字母和下劃線開(kāi)頭读整,其他都是字母、數(shù)字咱娶、下劃線
isdecimal() 是否只包含十進(jìn)制數(shù)字
isdigit() 是否全部數(shù)字(0~9)
isalnum() -> bool 是否是字母和數(shù)字組成
islower() 是否都是小寫(xiě)
isupper() 是否全部大寫(xiě)
isspace() 是否只包含空白字符

>>> "sdasdfsadf".isalpha()
True
>>> "abcd".isalpha()
True
>>> "abcd4234".isalpha()
False
>>> "abcd__4234".isidentifier()
True
>>> "abcd__423**4".isidentifier()
False

7.字符串格式化

7.1 字符串大小寫(xiě)

upper() -> 全部轉(zhuǎn)換為大寫(xiě)字母
lower() -> 全部轉(zhuǎn)換為小寫(xiě)字母
swapcase() -> 大小寫(xiě)交互

>>> s1 = 'aBcDeF'
>>> s1.upper()
'ABCDEF'
>>> s1.lower()
'abcdef'
>>> s1.swapcase()
'AbCdEf
7.2 字符串排版

title() -> str 標(biāo)題的每個(gè)單詞都大寫(xiě)
capitalize() -> str 首個(gè)單詞大寫(xiě)
center(width[,fillchar]) -> width:打印寬度 fillchar:填充的字符
zfill(width) -> str width 打印寬度米间,居右,左邊用0填充
ljust(width[,fillchar]) -> str 左對(duì)齊
rjust(width[,fillchar]) -> str 右對(duì)齊

>>> s1 = "I am a stone"
>>> s1.title()
'I Am A Stone'
>>> s1.capitalize()
'I am a stone'
>>> s1.center(20,'*')
'****I am a stone****'
>>> s1.center(4)
'I am a stone'
>>> s1.zfill(30)
'000000000000000000I am a stone'
>>> s1.ljust(30,'*')
'I am a stone******************'
>>> s1.rjust(30,'*')
'******************I am a stone'
7.3 format方法

format函數(shù)格式字符串用法

1. "{} {xxx}".format(*args,**kwargs) --> str 
2. args是位置參數(shù)膘侮,是一個(gè)元組
3. kwargs是關(guān)鍵字參數(shù)屈糊,是一個(gè)字典
4. 花括號(hào)表示占位符
5. {}表示按照順序匹配位置參數(shù),{n}表示取位置參數(shù)索引為n的值
6. {xxx}表示在關(guān)鍵字參數(shù)中搜索名稱一致的
7. {{}}表示打印花括號(hào)

位置參數(shù)
按照順序用位置參數(shù)替換前面的格式字符串的占位符中

>>> "{}:{}".format('192.168.1.100',8888)
'192.168.1.100:8888'

關(guān)鍵字參數(shù)或命名參數(shù)
位置參數(shù)按照序號(hào)匹配喻喳,關(guān)鍵字參數(shù)按照名詞匹配

>>> "{server} {1}:{0}".format(8888, '192.168.1.100', server='Web Server Info : ')
'Web Server Info :  192.168.1.100:8888'

元素訪問(wèn)

>>> "{0[0]}.{0[1]}".format(('stone','com'))
'stone.com'

對(duì)象屬性訪問(wèn)

>>> from collections import namedtuple
>>> Point = namedtuple('Point','x y')
>>> p1 = Point(4,5)
>>> "{{{0.x},{0.y}}}".format(p1)
'{4,5}'
>>> "{0.x}:{0.y}".format(p1)
'4:5'

字符串對(duì)齊

>>> '{0}*{1}={2:<2}'.format(3,2,2*3)
'3*2=6 '
>>> '{0}*{1}={2:<02}'.format(3,2,2*3)
'3*2=60'
>>> '{0}*{1}={2:>02}'.format(3,2,2*3)
'3*2=06'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')
'***********centered***********'

進(jìn)制

>>> "int:{0:d};hex:{0:x};oct:{0:o};bin:{0:b}".format(42)
'int:42;hex:2a;oct:52;bin:101010'
>>> "int:{0:d};hex:{0:#x};oct:{0:#o};bin:{0:#b}".format(42)
'int:42;hex:0x2a;oct:0o52;bin:0b101010'
>>> octets = [192,168,0,1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末另玖,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子表伦,更是在濱河造成了極大的恐慌,老刑警劉巖慷丽,帶你破解...
    沈念sama閱讀 219,366評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蹦哼,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡要糊,警方通過(guò)查閱死者的電腦和手機(jī)纲熏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)锄俄,“玉大人局劲,你說(shuō)我怎么就攤上這事∧淘” “怎么了鱼填?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,689評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)毅戈。 經(jīng)常有香客問(wèn)我苹丸,道長(zhǎng),這世上最難降的妖魔是什么苇经? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,925評(píng)論 1 295
  • 正文 為了忘掉前任赘理,我火速辦了婚禮,結(jié)果婚禮上扇单,老公的妹妹穿的比我還像新娘商模。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布施流。 她就那樣靜靜地躺著凉倚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪嫂沉。 梳的紋絲不亂的頭發(fā)上稽寒,一...
    開(kāi)封第一講書(shū)人閱讀 51,727評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音趟章,去河邊找鬼杏糙。 笑死,一個(gè)胖子當(dāng)著我的面吹牛蚓土,可吹牛的內(nèi)容都是我干的宏侍。 我是一名探鬼主播,決...
    沈念sama閱讀 40,447評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼蜀漆,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼谅河!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起确丢,我...
    開(kāi)封第一講書(shū)人閱讀 39,349評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤绷耍,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后鲜侥,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體褂始,經(jīng)...
    沈念sama閱讀 45,820評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評(píng)論 3 337
  • 正文 我和宋清朗相戀三年描函,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了崎苗。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,127評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡舀寓,死狀恐怖胆数,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情互墓,我是刑警寧澤必尼,帶...
    沈念sama閱讀 35,812評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站轰豆,受9級(jí)特大地震影響胰伍,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜酸休,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評(píng)論 3 331
  • 文/蒙蒙 一骂租、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧斑司,春花似錦渗饮、人聲如沸但汞。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,017評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)私蕾。三九已至,卻和暖如春胡桃,著一層夾襖步出監(jiān)牢的瞬間踩叭,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,142評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工翠胰, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留容贝,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,388評(píng)論 3 373
  • 正文 我出身青樓之景,卻偏偏與公主長(zhǎng)得像斤富,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子锻狗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容