1.什么是字符串
a.使用單引號或者雙引號括起來的字符集
就是字符串。
b.引號中單獨
的符號、數(shù)字、字母等叫字符
c.轉(zhuǎn)義字符:可以用來表示一些有特殊功能或是特殊意義的字符
(通過在固定
的字符前加反斜杠'\'
)
\'->'
\\->\
\n->換行
\t->制表符
\"->"
在計算字符串長度的時候,轉(zhuǎn)義字符代表一個字符
eg:'\n'
就是一個字符
'123'
數(shù)字字符串
'ancn'
'^7&#sj'
'中文漢字'
' '空格
str2 = '\''
print(str2)
str1 = '床前明月光,\n疑是地上霜。'
print(str1)
ouput
:`,床前明月光,\n疑是地上霜。
2.阻止轉(zhuǎn)義
可以通過在字符串前面加r或者R,來阻止轉(zhuǎn)義字符轉(zhuǎn)義
str1 = r'\\'
print(str1)
str2 = '\\\\'
print(str2)
str3 = '\\1\n2'
print(str3)
str4 = r'\\1\n2'
print(str4)
output
:\\,\\,\1\n2,\\1\n2
3.python中字符串中的字符是Unicode編碼(C語言,ASCII碼)
Unicode編碼:使用16位對一個字符進行編碼,編碼的目的是讓字符可以存儲到計算機中。最大整數(shù)65536
Unicode碼中包含了ASCII碼,可以表示世界上所有的語言和符號
a.獲取一個字符的Unicode碼
ord('字符')
ord1 = ord('張')
ord2 = ord('書')
ord3 = ord('語')
print(hex(ord1))
print(hex(ord2),hex(ord3))
print(ord('張'),ord('書'),ord('語'))
print(hex(ord('張')),hex(ord('書')),hex(ord('語')))
output
:0x5f20
0x4e66 0x8bed
24352 20070 35821
0x5f20 0x4e66 0x8bed
b.將Unicode碼轉(zhuǎn)換成字符
chr(編碼值)
print(chr(0x4eff))
print(chr(0x5f20))
output
:仿
張
字符串比較大小的時候,從字符開始依次往后比較每個字符的大小,直到遇到字符不一樣為止。
比較字符大小的時候,實質(zhì)比的是它們的編碼的大小。
print('abc'>'b')
print('Z'>'a','z'>'a')
print('a'>'ab')
print('Z'>'z')
print('ac'>'ab')
print('a'>'張')
output
:False
False,True
False
False
True
False
python的字符,實質(zhì)是一個有序
的字符序列。
1.獲取字符串長度:(長度->字符串中字符的個數(shù))
len
是獲取序列長度的內(nèi)置函數(shù)
count1 = len('abc123');count2 = len('abc\n123')
print(count1,count2)
print(len('abc123'),len('abc\n123'))
output
:6,7
6,7
2.通過下標獲取字符串中的某一個字符(索引值=長度-1)
字符串中每個字符都對應一個下標(索引),我們可以通過索引值去獲取固定的某個字符:print(字符串[索引值])
。
'abc' --> a->0,b->1,c->2
str1 = 'abc'
print(str1[0]) #a
print(str1[2]) #c
str2 = 'dy\nup'
print(str2[4])
output
:a,c,p
下標的范圍:0 ~ 字符串長度-1;-1 ~ -字符串長度
獲取字符的時候,索引值不能超過索引的范圍,否則會報錯IndexError
str1 = 'abc'
print(str1[2])
output
:c
print(str1[3]) # IndexError: string index out of range
print(str1[-1])
output
:c
獲取字符串str1中的最后的字符
print(str1[-2])
output
:b
獲取字符串str1中的倒數(shù)第二個字符
3.獲取字符串中的部分字符(切片):(通過字符獲取下標?)
字符串[開始下標:結(jié)束下標]-->獲取字符串中從開始下標到結(jié)束下標中所有字符(包含開始下標,不包括結(jié)束下標)
字符串[開始下標:結(jié)束下標:步進]
字符串[開始下標:結(jié)束下標]===字符串[開始下標:結(jié)束下標:1]
a.開始和結(jié)束下標都有值:開始下標對應的字符,要在結(jié)束下標對應的字符前面(步進是正數(shù))
str3 = 'hello Pyth on'
# 01234567891011
print(str3[6:12])
print(str3[-6:12])
print(str3[11])
output
:Python,Python,n
b.開始下標省略:從字符串的最前面取到結(jié)束下標前
print(str3[:4])
output
:hell
c.結(jié)束下標省略:從開始位置獲取到字符串結(jié)束
print(str3[4:])
output
:o Python
e.兩個都省略:獲取整個字符串的內(nèi)容
print(str3[:])
output
:hello Python
f.
print(str3[::2]) # 0-10: 0 0+2 2+2 4+2 6+2 8+2
output
:hloPto
(了解)當步進是負數(shù)的時候,即從右往左取
print(str3[3::-1]) # 3 3-1=2 2-1=1 1-1=0
print(str3[3:1:-1])
print(str3[::-1]) # 字符串倒序
print(str3[3::-1]) # 3 3-1=2 2-1=1 1-1=0
print(str3[:3:-1])
print(str3[11:3:-1])
output
:lleo,
ll,
nohtyP olleh,
lleh,
nohtyp o,從最要邊往[3]取
nohtyP o,
1. +:字符串拼接
字符串1 + 字符串2
str1 = 'hello' + ' ' + 'Python'
print(str1)
output
:hello Python
注意:+號兩邊要么都是數(shù)字,要么都是字符串。不能是一個數(shù)字,一個字符串。
print(12+'34') 報錯:TypeError: unsupported operand type(s) for +: 'int' and 'str'
2.*:讓字符串重復
字符串 * 整數(shù)
str1 = 'abc' * 3
print(str1)
output
:abcabcabc
3.in
字符串1 in 字符換2:判斷字符串1是否在字符串2中-->在就是True,不在就是False
result = 'a' in 'abc'
print(result)
output
:True
4.not in
字符串1 not in 字符串2:判斷字符串1是否不在字符串2中-->不在就是True,在就是False
result = '123' not in 'abc'
print(result)
output
:True
5.格式字符串
格式:'占位符1占位符2'%(值1,值2)
str1 = 'abc%s123' %('>>>')
str2 = 'abc%s12%s3' % ('>>>','!!!')
print(str1,str2)
output
:abc>>>123, abc>>>12!!!3
%s --> 字符串占位符(格式符)
%d --> 整數(shù)占位符(格式符)
%f --> 浮點占位符
%c --> 長度是1的字符串占位符(字符占位符)---可以給一個字符,也可以給字符的編碼值
str2 = '-%s-%d-%f-%c' %('我是字符串',123,12.4,'k')
print(str2)
str3 = '-%s-%d-%f-%c-%c' %('我是字符串',123,12.4,'k',97)
print(str3)
output
:-我是字符串-123-12.400000-k,-我是字符串-123-12.4-k-a
%.nf:使用n值限值小數(shù)點后面的小數(shù)的位數(shù)(默認六位小數(shù))
str3 = '金額:%.2f元' %(100)
print(str3)
output
:金額:100.00元
如果后面沒有加%,那么這個字符串只是一個普通的字符串
str3 = '金額:%.2f元'
print(str3)
output
:金額:%.2f元
%x和%X-->十六進制數(shù)據(jù)占位符
number = 15
XXX的十六進制是XXXXX
str4 = '%d的十六進制是0X%x' % (number,number)
print(str4)
output
:15的十六進制是0Xf
6.格式化輸出
name = 'QQ'
age = 18
xx今年xx歲
print('%s今年%d歲' % (name,age))
print('%dAAA' % (2))
number = 10
str4 = '%d的八進制是%o' % (number,number)
print(str4)
nub=10
print('%d的八進制是%o' % (nub,nub))
output
:QQ今年18歲,2AAA,10的八進制是12,10的八進制是12
字符串相關(guān)方法的通用格式:字符串.函數(shù)()
1.capitalize:將字符串的首字母轉(zhuǎn)換成大寫字母,并且創(chuàng)建一個新的字符串返回(以前的字符串并沒變)。
str1 = 'abc'
new_str = str1.capitalize()
print(str1,new_str)
str1 ='abc'
print(str1.capitalize())
output
:abc,Abc,Abc——————這里的str1沒變,生成了一個新的new_str=str.capitalize=Abc
2.center(width,fillchar):將原字符串變成指定的長度并且內(nèi)容居中,且fillchar為填充的字符。
new_str = str1.center(7,'*')
print(str1,new_str)
output
:abc,** abc **
3.rjust(width,fillchar):同上,右對齊
new_str = str1.rjust(7,'*')
print(new_str)
output
:****abc
產(chǎn)生學號
number = 19 #py1805009
str(數(shù)據(jù)):將任何其他的數(shù)據(jù)轉(zhuǎn)換成字符串
num_str = str(number)
print(num_str,type(num_str))
output
:19,<class 'str'>
讓字符串變成寬度為3,內(nèi)容右對齊,剩下部分使用'0'填充
new_str = num_str.rjust(3,'0')
print(new_str)
new_str = 'py1805'+new_str
print(new_str)
output
:019,py1805019
4.ljust(width,fillchar):左對齊
number = 18
num_str = str(number)
print(num_str,type(num_str))
new_str = num_str.ljust(9,'0')
print(new_str)
output
:18,<class 'str'>,180000000
5.字符串1.join(字符串2):在字符串2中的每個字符之間插入一個字符串1
new_str = 'aaaa'.join('bbb')
print(new_str)
output
:baaaabaaaab
# 6.maketrans()
print(str.maketrans('aaa','bbb'))
print(max("abc"))
output
:{97: 98},c
1 |capitalize()|將字符串的第一個字符轉(zhuǎn)換為大寫
2| center(width, fillchar)|返回一個指定的寬度 width 居中的字符串,fillchar 為填充的字符,默認為空格。
3| count(str, beg= 0,end=len(string))|返回 str 在 string 里面出現(xiàn)的次數(shù),如果 beg 或者 end 指定則返回指定范圍內(nèi) str 出現(xiàn)的次數(shù)
4| bytes.decode(encoding="utf-8", errors="strict")|Python3 中沒有 decode 方法,但我們可以使用 bytes 對象的 decode() 方法來解碼給定的 bytes 對象,這個 bytes 對象可以由 str.encode() 來編碼返回。
5| encode(encoding='UTF-8',errors='strict')|以 encoding 指定的編碼格式編碼字符串,如果出錯默認報一個ValueError 的異常,除非 errors 指定的是'ignore'或者'replace'
6| endswith(suffix, beg=0, end=len(string))|檢查字符串是否以 obj 結(jié)束,如果beg 或者 end 指定則檢查指定的范圍內(nèi)是否以 obj 結(jié)束,如果是,返回 True,否則返回 False.
7| expandtabs(tabsize=8)|把字符串 string 中的 tab 符號轉(zhuǎn)為空格,tab 符號默認的空格數(shù)是 8 。
8| find(str, beg=0 end=len(string))|檢測 str 是否包含在字符串中,如果指定范圍 beg 和 end ,則檢查是否包含在指定范圍內(nèi),如果包含返回開始的索引值,否則返回-1
9| index(str, beg=0, end=len(string))|跟find()方法一樣,只不過如果str不在字符串中會報一個異常.
10| isalnum()|如果字符串至少有一個字符并且所有字符都是字母或數(shù)字則返 回 True,否則返回 False
11| isalpha()|如果字符串至少有一個字符并且所有字符都是字母則返回 True, 否則返回 False
12 |isdigit()|如果字符串只包含數(shù)字則返回 True 否則返回 False..
13 |islower()|如果字符串中包含至少一個區(qū)分大小寫的字符,并且所有這些(區(qū)分大小寫的)字符都是小寫,則返回 True,否則返回 False
14 |isnumeric()|如果字符串中只包含數(shù)字字符,則返回 True,否則返回 False(中文數(shù)字也可以)
15 |isspace()|如果字符串中只包含空白,則返回 True,否則返回 False.
16| istitle()|如果字符串是標題化的(見 title())則返回 True,否則返回 False
17|isupper()|如果字符串中包含至少一個區(qū)分大小寫的字符,并且所有這些(區(qū)分大小寫的)字符都是大寫,則返回 True,否則返回 False
18| join(seq)|以指定字符串作為分隔符,將 seq 中所有的元素(的字符串表示)合并為一個新的字符串
19| len(string)|返回字符串長度
20| ljust(width[, fillchar])|返回一個原字符串左對齊,并使用 fillchar 填充至長度 width 的新字符串,fillchar 默認為空格。
21 |lower()|轉(zhuǎn)換字符串中所有大寫字符為小寫.
22 |lstrip()|截掉字符串左邊的空格或指定字符。
23| maketrans()|創(chuàng)建字符映射的轉(zhuǎn)換表,對于接受兩個參數(shù)的最簡單的調(diào)用方式,第一個參數(shù)是字符串,表示需要轉(zhuǎn)換的字符,第二個參數(shù)也是字符串表示轉(zhuǎn)換的目標。
24 |max(str)|返回字符串 str 中最大的字母。
25| min(str)|返回字符串 str 中最小的字母。
26 |replace(old, new [, max])|把 將字符串中的 str1 替換成 str2,如果 max 指定,則替換不超過 max 次。
27 |rfind(str, beg=0,end=len(string))|類似于 find()函數(shù),不過是從右邊開始查找.
28 |rindex( str, beg=0, end=len(string))|類似于 index(),不過是從右邊開始.
29| rjust(width,[, fillchar])|返回一個原字符串右對齊,并使用fillchar(默認空格)填充至長度 width 的新字符串
30 |rstrip()|刪除字符串字符串末尾的空格.
31 |split(str="", num=string.count(str))|num=string.count(str)) 以 str 為分隔符截取字符串,如果 num 有指定值,則僅截取 num 個子字符串
32 |splitlines([keepends])|按照行('\r', '\r\n', \n')分隔,返回一個包含各行作為元素的列表,如果參數(shù) keepends 為 False,不包含換行符,如果為 True,則保留換行符。
33 |startswith(str, beg=0,end=len(string))|檢查字符串是否是以 obj 開頭,是則返回 True,否則返回 False。如果beg 和 end 指定值,則在指定范圍內(nèi)檢查。
34 |strip([chars])|在字符串上執(zhí)行 lstrip()和 rstrip()
35 |swapcase()|將字符串中大寫轉(zhuǎn)換為小寫,小寫轉(zhuǎn)換為大寫
36 |title()|返回"標題化"的字符串,就是說所有單詞都是以大寫開始,其余字母均為小寫(見 istitle())
37 |translate(table, deletechars="")|根據(jù) str 給出的表(包含 256 個字符)轉(zhuǎn)換 string 的字符, 要過濾掉的字符放到 deletechars 參數(shù)中
38 |upper()|轉(zhuǎn)換字符串中的小寫字母為大寫
39 |zfill (width)|返回長度為 width 的字符串,原字符串右對齊,前面填充0
40 |isdecimal()|檢查字符串是否只包含十進制字符,如果是返回 true,否則返回 false。
if語句
結(jié)構(gòu):
1.
if 條件語句:
? ? ? ? ? ? ?條件語句結(jié)果為True執(zhí)行的代碼塊
執(zhí)行過程:先判斷條件語句是否為True,如果為True就執(zhí)行if語句后:后面對應的一個縮進的所有的代碼。
為False,就不執(zhí)行冒號后面一個縮進中的代碼塊,直接執(zhí)行后續(xù)的其他語句。
條件語句:可以是任何有值的表達式,但是一般是布爾值
if:關(guān)鍵字
if False:
print('代碼1')
print('代碼2')
print('代碼3')
print('代碼4') #不屬于if語句中的代碼塊
output
:代碼4
練習:用一個變量保存時間(50米短跑時間),如果時間小于8s,就打印及格
time = 7
if time < 8:
print('及格') # 只有條件成立的時候才會執(zhí)行
print(time) #不管if語句的條件為否,這個語句都會執(zhí)行
output
:7
if 條件語句:
? ? ? ? ? ? ?語句塊1
else:
? ? ? ? ? ? ?語句塊2
執(zhí)行過程:先判斷條件語句是否為True,如果為True就執(zhí)行語句塊1,如果為False就執(zhí)行語句塊2.
練習:用一個變量保存成績,如果成績大于等于60,就打印及格,否則就打印不及格
score = 88
if score >= 60:
print('及格')
else:
print('不及格')
output
:及格