1.字符串
a.使用單引號或雙引號括起來的字符集就是字符串
b.引號中單獨的符號、數字、字母等叫字符
c.轉義字符:可以用來表示一些有特殊功能或者是特殊意義的字符(通過在固定的字符前加),轉義字符在計算字符串長度時,轉義字符代表一個字符。
-->'
\ -->
\n -->換行
\t -->制表符
" -->"
例:
'123' # 數字字符串
'ahcn'
'^&*&sf'
'坑逼'
' '
str2='\''
print(str2)
str3='\\'
print(str3)
str1='床前明月光,\n疑是地上霜。'
print(str1)
結果
'
\
床前明月光,
疑是地上霜。
2.阻止轉義
可以通過在字符串前面加r或R,來阻止轉義字符轉義
例:
str4=r'\\'
print(str4)
結果:
\\
3.Python中字符串的字符是Unicode編碼
Unicode編碼:使用16位對一個字符進行編碼編,編碼的目的是讓字符可以存儲到計算機中。Unicode碼中包含了ASSCII碼,可以表示世界上所有的語言和符號
a.獲取一個字符的Unicode碼,ord('字符')
例:
print(hex(ord('與')))
結果:
0x4e0e
b.將Unicode碼轉換成字符,chr(編碼值)
例:
print(chr(0x4e00))
結果:
一
c.字符串比較大小
從字符串的第一個字符開始依次往后比較每個字符的大小,直到遇到字符不一樣為止。比較字符大小的時候, 實質比的是他們編碼的大小
例:
print('abc'>'b')
print('abc'>'aa')
結果:
False
True
4.獲取字符串長度
長度 :字符串的字符個數
len():是獲取序列長度的內置函數
例:
count=len('abc\n123')
print(count)
結果:
7
5.獲取字符
索引:字符串中每一個字符都對應一個下標(索引),我們可以通過索引值
例:
'abc' ---> a:0 ,b:1 ,c:2
格式:字符串[索引值]
例:
str1='abc'
print(str1[0]) # a
print(str1[1]) #b
str2="dy\nup"
print(str2[4])
結果:
a
b
p
注意:下標的范圍:0~字符串的長度-1。獲取字符串中的字符時,索引值不能超過索引的范圍,否則會報IndexError
索引值為負數時:
例:
print(str1[-1]) # 獲取字符串str1中的最后一個字符
print(str1[-2]) # 獲取字符串str1中的倒數第二個字符
結果:
c
b
6.獲取部分字符
格式1:字符串[開始下標:結束下標]==字符串[開始下標:結束下標:1] --->獲取字符串中包括開始下標但不包括結束下標之間的所有字符字
格式2:符串[開始下標:結束下標:步進]
a.開始下標對應的字符,要在結束下標對應的字符前面(步進是整數)
例:
str3='hello ren za'
print(str3[6:9])
str4='hello Python'
print(str4[6:12]) # Python
print(str4[-6:12]) # Python
結果:
ren
Python
Python
b.開始下標省略:從字符串的最前面取到結束下標前一個字符
例:
print(str4[:4])
結果:
hell
c.結束下標省略:從開始位置取到字符串結束
print(str4[4:])
結果:
o Python
e.兩個都省略:獲取整個字符串的內容
例:
print(str4[:])
結果:
hello Python
f.有步進
例:
print(str4[::2]) # hloPto
結果:
hloPto
g.當步進是負數時,開始下標的字符可以取而結束下標的字符取不到。當結束下標和開始下標省略時,全取
例:
print(str4[4::-1]) #
print(str4[:4:-1])
print(str4[4:0:-1])
print(str4[::-1])
print(str4[4::-2])
print(str4[::-2])
結果:
olleh
nohtyP
olle
nohtyP olleh
olh
nhy le
7.字符串拼接
1)運算符+
注意:加號兩邊要么都是數字要么都是字符串,不能一邊是數字一邊是字符串
例:
str1='hello'+' '+'Python'
print(str1)
結果:
hello Python
2)運算符*
讓字符串重復
格式:字符串*整數
例:
str2='hello '*3
print(str2)
str2='a'*10
print(str2)
結果:
hello hello hello
aaaaaaaaaa
3)in
判斷in前邊字符串是否在in后邊字符串中-->True 或False
格式:字符串1 in 字符串2
例:
result='aa'in 'aaffdd'
print(result)
結果:
True
4)not in
判斷not in前邊字符串是否不在not in后邊字符串中-->True False
格式:字符串1 not in 字符串2
例:
result='123' not in 'abc'
print(result)
結果:
True
5) 格式字符串
格式:'%s'(表示站位符) %(值)(可以有多個站位符)
例:
str3='abd%swrweff%s' %('123','dd232')
print(str3)
結果:
abd123wrweffdd232
#%s -->字符串占位符(格式符)
#%d -->整數占位符(格式符)
#%f -->浮點數占位符
#%c -->長度是1的字符串占位符(字符站位符)
# 可以給一個字符,也可以給字符的編碼值
str4='-%s-%d-%f-%c-'%('我是字符串',1234,12.5,'k')
print(str4)
# %.nf:使用n值限制小數點后面的位數(默認六位小數)
str5='金額:%.2f元'%(100)
print(str5)
# 如果占位符后面沒加%(),那么這個字符串只是普通的字符串
str6='金額:%.2f元'
print(str6)
# %x和%X--->十六進制數據占位符
number=15
str7='%d的十六進制是0x%x'%(number,number)
print(str7)
結果:
-我是字符串-1234-12.500000-k-
金額:100.00元
金額:%.2f元
15的十六進制是0xf
str9='-%c-%s-%d-%f-%u-%o-%x-%X-%e-%E-%g-%G'%('k','jgakshd',-120,12.0,34,99,15,15,15.8,15.8,15.8,15.8)
print(str9)
結果:
-k-jgakshd--120-12.000000-34-143-f-F-1.580000e+01-1.580000E+01-15.8-15.8
6)格式化輸出
name='路飛'
age=23
print('%s今年%d歲'%(name,age))
str8='他是%g歲'%(7.99)
結果:
路飛今年23歲
8.字符串方法
1)capitalize()函數
將字符的第一個字符轉換為大寫
str='hello ren si yu'
print(str)
new_str=str.capitalize()
print(new_str)
結果:
hello ren si yu
Hello ren si yu
2)center(width,fillchar)
返回一個長度為width且指定字符串居中的字符串,空余位置用fillchar填充,fillchar為填充的字符,默認為空格
str='hello'
print(str)
new_str=str.center(10,'*')
print(new_str)
結果:
hello
hello*
3)count(str,beg=0,end=len(string))
返回 str 在 string 里面出現的次數,如果 beg 或者 end 指定則返回指定范圍內 str 出現的次數
str='www.runoob.com'
print(str.count('o'))
print(str.count('www',0,len(str)))
print(str.count('www',0,10))
結果:
3
1
1
4)bytes.decode
decode() 方法以指定的編碼格式解碼 bytes 對象。默認編碼為 'utf-8'。
str='任思宇'
str_utf8=str.encode("UTF-8")
str_gbk=str.encode("GBK")
print(str)
print("UTF-8編碼:",str_utf8)
print("GBK編碼:",str_gbk)
print("UTF-8解碼:",str_utf8.decode('UTF-8','strict'))
print("GBK解碼:",str_gbk.decode('GBK','strict'))
結果:
任思宇
UTF-8編碼: b'\xe4\xbb\xbb\xe6\x80\x9d\xe5\xae\x87'
GBK編碼: b'\xc8\xce\xcb\xbc\xd3\xee'
UTF-8解碼: 任思宇
GBK解碼: 任思宇
5endwith(suffix,beg=0,end=len(string))
檢查字符串是否以 obj 結束,如果beg 或者 end 指定則檢查指定的范圍內是否以 obj 結束,如果是,返回 True,否則返回 False.
str='hello ren si yu'
new_str=str.endswith('yu')
print(new_str)
new_str=str.endswith('s',0,11)
print(new_str)
new_str=str.endswith('u',0,len(str))
print(new_str)
結果:
True
True
True
6)expandtabs(tabsize=8)
str='tab is\tsb'
print(str)
print(str.expandtabs())
print(str.expandtabs(8)) #默認為8
print(str.expandtabs(16))
結果:
tab is sb
tab is sb
tab is sb
tab is sb
7)find(str,beg,end=len(string))
檢測 str 是否包含在字符串中,如果指定范圍 beg 和 end ,則檢查是否包含在指定范圍內,如果包含返回開始的索引值,否則返回-1
str='hello sb go go'
new_str=str.find('go')
print(new_str)
new_str=str.find('go',0,len(str))
print(new_str)
new_str=str.find('goo',0,len(str))
print(new_str)
new_str=str.find('go',11,14)
print(new_str)
結果:
9
9
-1
12
8)index(str,beg,end=len(string))
檢測 str 是否包含在字符串中,如果指定范圍 beg 和 end ,則檢查是否包含在指定范圍內,如果包含返回開始的索引值,否則會出現異常
str='hello sb go go'
new_str=str.index('go')
print(new_str)
new_str=str.index('go',0,len(str))
print(new_str)
new_str=str.index('go',11,14)
print(new_str)
# new_str=str.index('goo',0,len(str))
# print(new_str)
結果:
9
9
12
9)isalnum()
如果字符串至少有一個字符并且所有字符都是字母或數字則返 回 True,否則返回 False
str='hello'
str1=' '
str2='123'
print(str.isalnum(),str1.isalnum(),str2.isalnum())
結果:
True False True
10)isalpha
如果字符串至少有一個字符并且所有字符都是字母則返回 True, 否則返回
False
str='hello'
str1=' '
str2='123'
print(str.isalpha(),str1.isalpha(),str2.isalpha())
結果:
True False False
11)isdigit()
如果字符串只包含數字則返回 True 否則返回 False
str='hello'
str1=' '
str2='123'
print(str.isdigit(),str1.isdigit(),str2.isdigit())
結果:
False False True
12)islower()
如果字符串中包含至少一個區分大小寫的字符,并且所有這些(區分大小寫的)字符都是小寫,則返回 True,否則返回 False
str='Adjfi'
str1=' '
str2='124'
str3='dfsd'
print(str.islower(),str1.islower(),str2.islower(),str3.islower())
結果:
False False False True
13)isnumeric()
如果字符串中只包含數字字符,則返回 True,否則返回 False
str='3435djfi'
str1=' '
str2='124'
str3='dfsd'
print(str.isnumeric(),str1.isnumeric(),str2.isnumeric(),str3.isnumeric())
結果:
False False True False
14)isspace
如果字符串中只包含空白,則返回 True,否則返回 False.
str='3435djfi'
str1=' '
str2='124'
str3='dfsd'
print(str.isspace(),str1.isspace(),str2.isspace(),str3.isspace())
結果:
False True False False
15)istitle()
如果字符串是標題化的(見 title())則返回 True,否則返回 False
str='Axin'
str1='dfd'
str2=' '
str3='342352'
print(str.istitle(),str1.istitle(),str2.istitle(),str3.istitle())
結果:
True False False False
16)isupper()
如果字符串中包含至少一個區分大小寫的字符,并且所有這些(區分大小寫的)字符都是大寫,則返回 True,否則返回 False
str='ASFFS'
str1='dfd'
str2=' '
str3='342352'
print(str.isupper(),str1.isupper(),str2.isupper(),str3.isupper())
結果:
True False False False
17)join(seq)
以指定字符串作為分隔符,將 seq 中所有的元素(的字符串表示)合并為一個新的字符串
str='*'
str1=''
seq = ("r", "u", "n", "o", "o", "b")
print(str.join(seq))
print(str1.join(seq))
結果:
runoo*b
runoob
18)len(string)
返回字符串長度
str='hello'
print(len(str))
結果:
5
19)ljust(width,fillchar)
返回一個原字符串左對齊,并使用 fillchar 填充至長度 width 的新字符串,fillchar 默認為空格
str='yello'
print(str.ljust(10,'%'))
結果:
yello%%%%%
20)lower()
轉換字符串中所有大寫字符為小寫.
str="HELLO"
print(str.lower())
結果:
hello
21)upper()
轉換字符串中所有大寫字符為大寫.
str="hello ello"
print(str.upper())
結果:
HELLO ELLO
22)lstrip()
截掉字符串左邊的空格或指定字符。
str='\nhello\n'
print(str)
print(str.lstrip())
結果:
hello
hello
23)rstrip()
截掉字符串右邊的空格或指定字符。
str='\nhello\n'
print(str)
print(str.rstrip())
結果:
hello
hello
24)strip()
截掉字符串兩邊的空格或指定字符。
str='\nhello\n'
print(str)
print(str.strip())
結果:
hello
hello
25)maketrans()
創建字符映射的轉換表,對于接受兩個參數的最簡單的調用方式,第一個參數是字符串,表示需要轉換的字符,第二個參數也是字符串表示轉換的目標。
str='hello yello sb www.com'
new_str=str.maketrans('se','12')
print(str.translate(new_str))
結果:
h2llo y2llo 1b www.com
26)max(str)
返回字符串 str 中最大的字母。
str='hello'
str1='235'
print(max(str),max(str1))
結果:
o 5
27)min(str)
返回字符串 str 中最小的字母
str='hello'
str1='235'
print(min(str),min(str1))
結果:
e 2
28)rfind(str,beg=0,end=len(string))
類似于 find()函數,不過是從右邊開始查找.
str="hello ren si yu"
print(str.rfind('si',0,len(str)))
結果:
10
29rjust(width,fillchar)
返回一個原字符串右對齊,并使用fillchar(默認空格)填充至長度 width 的新字符串
str='yello'
print(str.rjust(20,'%'))
結果:
%%%%%%%%%%%%%%%yello
30)rindex(str,beg=0,end=len(string))
類似于 index(),不過是從右邊開始.
str='hello ren si yu'
print(str.rindex('re',0,len(str)),str.rindex('en',0,len(str)))
# print(str.rindex('enn',0,len(str)))
結果:
6 7
31)replace(old,new,max)
把 將字符串中的 str1 替換成 str2,如果 max 指定,則替換不超過 max 次。
str='ok www is ok or yes ok'
print(str.replace('ok','12',2))
結果:
12 www is 12 or yes ok
32)split(str="",num=string,count(str))
num=string.count(str)) 以 str 為分隔符截取字符串,如果num 有指定值,則僅截取 num 個子字符串str -- 分隔符,默認為所有的空字符,包括空格、換行(\n)、制表符(\t)等。num -- 分割次數。
str='hello ren si yu you are sb'
print(str.split())
print(str.split('u',str.count('u')))
print(str.split('u',2))
結果:
['hello', 'ren', 'si', 'yu', 'you', 'are', 'sb']
['hello ren si y', ' yo', ' are sb']
['hello ren si y', ' yo', ' are sb']
33)splitlines([keepends])
按照行('\r', '\r\n', \n')分隔,返回一個包含各行作為元素的列表,如果參數 keepends 為 False,不包含換行符,如果為 True,則保留換行符。
str='ab c\n\nde fg\rkl\r\n'
print(str)
print(str.splitlines())
print(str.splitlines(True))
print(str.splitlines(False))
結果:
ab c
de fg
kl
['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
['ab c', '', 'de fg', 'kl']
34)startswith(str,beg=0,end=len(string))
檢查字符串是否是以 obj 開頭,是則返回 True,否則返回 False。如果beg 和 end 指定值,則在指定范圍內檢查。
str='hello ren si yu you are sb'
print(str.startswith('hello',0,len(str)))
print(str.startswith('re',6,len(str)))
print(str.startswith('re',5,10))
結果:
True
True
False
35)swapcase()
將字符串中大寫轉換為小寫,小寫轉換為大寫
str='HEllo'
print(str)
print(str.swapcase())
結果:
HEllo
heLLO
36)title()
返回"標題化"的字符串,就是說所有單詞都是以大寫開始,其余字母均為小寫(見 istitle())
str='hello ren si yu you are sb'
print(str.title())
結果:
Hello Ren Si Yu You Are Sb
9.if語句
條件語句結果為True執行的代碼塊
執行過程:先判斷條件語句是否為True,如果為True就執行if語句:后面對應的一個縮進的所有代碼。為False,就不執行冒號后面的一個縮進的代碼塊,直接執行后繼的其他語句
條件語句:可以是任何有值的表達式,但一般是布爾值
1)格式1:
if True:
print('代碼1')
print('代碼2')
print('代碼3')
print('代碼4')
練習:用一個變量保存時間(50米短跑),如果時間小于8秒則打印及格
time=7
if time>=8:
print('不及格')
else:
print('及格')
print(time)
結果
及格
7
2)格式2:
if 條件語句:
語句塊1
else:
語句塊2
執行過程:先判斷條件語句是否為True,如果為True就執行語句塊1,否則執行語句塊2
用一個變量保存成績,如果成績打于60,則打印及格,否則打印不及格
grade=79
if grade>=60:
print('及格')
else:
print('不及格')
結果:
及格