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