基本類型:字符串
文本的表示
字符串就是把一個(gè)個(gè)文字的字符“串 起來(lái)”的數(shù)據(jù)
- 字符串是容器型數(shù)據(jù)類型, 將單引號(hào)或者雙引號(hào)作為容器的標(biāo)志, 元素不需要用逗號(hào)隔開: '元素1元素2元素3...'
字符串是不可變的(不支持增刪改);字符串是有序的(支持下標(biāo)操作) - 字符串中的元素: 只能是文本符號(hào)(所有計(jì)算機(jī)能表達(dá)出來(lái)的符號(hào)都可以作為字符串的元素,包含有拉丁字母、數(shù)字、標(biāo)點(diǎn)符號(hào)、 特殊符號(hào),以及各種語(yǔ)言文字字符),一個(gè)符號(hào)對(duì)應(yīng)一個(gè)元素
'內(nèi)蒙', 'abxy','!@#$%', '↑?', '123456' - 字符串中每一個(gè)獨(dú)立的元素又叫:字符;python中只有字符的概念,但是沒有字符對(duì)應(yīng)的數(shù)據(jù)類型
表示字符串
- 用雙引號(hào)或者單引號(hào)都可以表示字符串, 但必須成對(duì)
- 多行字符串用三個(gè)連續(xù)單引號(hào)表示
# 空串
str1 = ''
str2 = ""
str3 = ''''''
str4 = """"""
print(type(str1), type(str2), type(str3), type(str4))
# 非空字符串
str5 = 'abc'
str6 = "你好"
str7 = '''你好,hello'''
str8 = """123,hi"""
特殊字符用轉(zhuǎn)義符號(hào)“\”表示
- 字符串中的字符分兩種:普通字符、轉(zhuǎn)義字符
- 普通字符 - 除了轉(zhuǎn)義字符串以外的字符
- 轉(zhuǎn)義字符 - 在指定符號(hào)前加\用來(lái)表示一些特殊功能和特殊意義的字符
轉(zhuǎn)義字符 | 描述 |
---|---|
(在行尾時(shí)) | 續(xù)行符 |
\\ | 反斜杠符 |
\' | 單引號(hào) |
\" | 雙引號(hào) |
\a | 響鈴 |
\b | 退格(backspace) |
\e | 轉(zhuǎn)義 |
\000 | 空 |
\n | 換行 |
\r | 縱向制表符 |
\t | 橫向制表符 |
\r | 回車 |
\f | 換頁(yè) |
\0yy | 八進(jìn)制yy的代表的字符,例如\012代表?yè)Q行,數(shù)值參見ASCII碼 |
\xyy | 十六進(jìn)制yy的代表的字符,例如\x0a代表?yè)Q行,數(shù)值參見ASCII碼 |
\uyyyy | 十六進(jìn)制yyyy代表的字符,例如\u4e00代表中文字符‘一’,參見Unicode編碼 |
\other | 其他字符以普通格式輸出 |
- 計(jì)算字符串長(zhǎng)度的時(shí)候一個(gè)轉(zhuǎn)義字符的長(zhǎng)度是1.
- 阻止轉(zhuǎn)義(r語(yǔ)法):在字符串的最前面,加上r/R,字符串中的所有的轉(zhuǎn)義字符都會(huì)無(wú)效
應(yīng)用1:windows路徑
應(yīng)用2:正則表達(dá)式
str1 = r'\tyytc\n3123\u4e00'
print(str1)
字符編碼
- 計(jì)算機(jī)在存儲(chǔ)數(shù)據(jù)的時(shí)候只能存數(shù)字,而且存的是數(shù)字的補(bǔ)碼
- 為了能夠讓計(jì)算機(jī)存儲(chǔ)文本數(shù)據(jù),給每個(gè)字符關(guān)聯(lián)了一個(gè)固定的數(shù)字,用來(lái)對(duì)這個(gè)字符進(jìn)行存儲(chǔ)。每個(gè)字符關(guān)聯(lián)的那個(gè)數(shù)字就是這個(gè)字符的
編碼值
。
編碼表
ASCII表:用一個(gè)字節(jié)來(lái)對(duì)字符進(jìn)行編碼(編碼范圍:0~127)
- 常見ASCII碼的大小規(guī)則:0~9 < A~Z < a~z。
- 數(shù)字比字母要小。如 “7”<“F”;
- 數(shù)字0比數(shù)字9要小,并按0到9順序遞增。如 “3”<“8” ;
- 字母A比字母Z要小,并按A到Z順序遞增。如“A”<“Z” ;
- 同個(gè)字母的大寫字母比小寫字母要小32。如“A”<“a” 。
- 幾個(gè)常見字母的ASCII碼大?。?“A”為65;“a”為97;“0”為 48
Unicode編碼表
- Unicode編碼表是對(duì)ASCII表的擴(kuò)展(Unicode編碼表中包含了ASCII表中所有的符號(hào))
- Unicode編碼表中包含了世界上所有國(guó)家所有民族所有的語(yǔ)言的符號(hào),總共65536個(gè)
中文范圍:4e00 ~ 9fa5
-
chr函數(shù):獲取指定編碼值對(duì)應(yīng)的字符 chr(0x0F00)
# 打印所有的中文 count = 0 for x in range(0x4e00, 0x9fa5): print(chr(x), end=' ') count += 1 if count % 40 == 0: print() print()
-
ord函數(shù) :獲取指定字符對(duì)應(yīng)的編碼值 ord('大')
print(ord('大'), ord('力'))
- \uxxxx 由十六進(jìn)制編碼值獲取對(duì)應(yīng)字符
str1 = '\u0f00你好!'
print(str1)
字符串和名字的區(qū)別
字符串是數(shù)據(jù)本身
名字是數(shù)據(jù)的標(biāo)簽
名字和字符串是“名”和“值”之間 的關(guān)系
- 一個(gè)字符串?dāng)?shù)值可以關(guān)聯(lián)多個(gè)名字 一個(gè)名字在同一時(shí)刻只能關(guān)聯(lián)一個(gè)字符串?dāng)?shù)值
- 字符串?dāng)?shù)值只能是字符串類型 名字則可以關(guān)聯(lián)任意類型的數(shù)值
字符串是一種序列
序列(sequence)
- 能夠按照整數(shù)順序排列的數(shù)據(jù)
序列的內(nèi)部結(jié)構(gòu):
- 可以通過(guò)從0開始的連續(xù)整數(shù)來(lái)索引單個(gè)對(duì)象;
- 可以執(zhí)行切片,獲取序列的一部分;
- 可以通過(guò)len函數(shù)來(lái)獲取序列中包含多少元素;
- 可以用加法“+”來(lái)連接為更長(zhǎng)的序列;
- 可以用乘法“*”來(lái)重復(fù)多次,成為更長(zhǎng)的序列;
- 可以用“in”來(lái)判斷某個(gè)元素是否在序列中存在。
字符串操作
獲取字符串中的元素(獲取字符)
- 下標(biāo)操作獲取單個(gè)元素
- 切片(slice)操作獲取多個(gè)元素 s[start? :end :step]
- 遍歷
str1 = 'how are you!'
# 獲取單個(gè)元素
print(str1[2])
print(str1[-1])
# 切片
print(str1[1:5]) # 'ow a'
print(str1[-3::-1]) # 'oy era woh'
# 遍歷
for x in str1:
print(x)
for index in range(len(str1)):
print(str1[index])
字符串相關(guān)運(yùn)算符
- “加法”和“乘法”
- +:將兩個(gè)字符串進(jìn)行連接,得到新的字符串。
- *:將字符串重復(fù)若干次,生成新的字符串。
str1 = 'app'
str2 = 'le'
print(str1 + str2) # apple
print(str2 * 2) # lele
- 判斷字符串內(nèi)容是否相同(==,!=)
str3 = 'app'
print(str3 == 'app') # True
print(str3 == 'pap') # False
- 判斷兩個(gè)個(gè)字符串的大小
- 兩個(gè)字符串比較大?。?比較的是第一組不相等的字符的編碼值的大小
str3 = 'aXYZ'
str4 = 'Ax12'
print(str3 > str4) # True
- 應(yīng)用:
- 判斷是否是數(shù)字字符: '0' <= char <= '9'
- 判斷是否是小寫字母:'a' <= char <= 'z'
- 判斷是否是大寫字母:'A' <= char <= 'Z'
- 判斷是否是字母:'a' <= char <= 'z' or 'A' <= char <= 'Z'
- 判斷是否是中文字符: '\u4e00' <= char <= '\u9fa5'
# 練習(xí)1:輸入一個(gè)字符串,統(tǒng)計(jì)字符串中字母和中文的個(gè)數(shù)
str6 = 'hello, 你好嗎?'
count1 = 0
count2 = 0
for x in str6:
if 'a' <= x <= 'z' or 'A' <= x <= 'Z':
count1 += 1
elif '\u4e00' <= x <= '\u9fa5':
count2 += 1
print('字母的個(gè)數(shù):', count1, '中文的個(gè)數(shù):', count2)
# 練習(xí)2:判斷輸入的字符串是否是純數(shù)字字符串
str7 = '728373'
for x in str7:
if not '0' <= x <= '9':
print('不是純數(shù)字字符串')
break
else:
print('是純數(shù)字字符串')
- 判斷字符串中是否包含某個(gè)字符串(in/not in)
print('yyz' in 'zyy') # False # 順序不一致
print('yyz' in 'yyzab') # True
print('a' in 'yyzab') # True
字符串相關(guān)函數(shù)
獲取字符串的長(zhǎng)度 len函數(shù)
max/min/sorted/reversed等,這些函數(shù)都適用于字符串
-
str(數(shù)據(jù)) - 將自定數(shù)據(jù)轉(zhuǎn)換成字符串
- 所有的數(shù)據(jù)都能轉(zhuǎn)換成字符串
- 將數(shù)據(jù)的打印值作為字符串的內(nèi)容
a ='absjfh' print(sorted(a)) # ['a', 'b', 'f', 'h', 'j', 's'] print(a) # absjfh str1 = r'\tabc' print(len(str1)) # 5 num = 100 str(num) # '100' str([1, 2, 3]) # '[1, 2, 3]'
字符串方法
- split:分割
# 字符串1.split(字符串2) - 字符串1將字符串2為切割點(diǎn)
# 字符串1.split(字符串2,N) - 字符串1將字符串2為切割點(diǎn),切N次
# 字符串1.rsplit(字符串2,N) - 字符串1將字符串2為切割點(diǎn),從右往左切N次
str1 = 'how are you? --- I am fine. thank you! and you?'
str2 = str1.split(' ')
str3 = str1.split(' ',2)
str4 = str1.rsplit(' ',2)
print(str2) # ['how', 'are', 'you?', '---', 'I', 'am', 'fine.', 'thank', 'you!', 'and', 'you?']
print(str3) # ['how', 'are', 'you? --- I am fine. thank you! and you?']
print(str4) # ['how are you? --- I am fine. thank you!', 'and', 'you?']
- join:合并
# 字符串.join(序列) 序列中的字符元素會(huì)用字符串連接
list1 = ['ap','p','le']
new_str1 = ''.join(list1)
new_str2 = '+'.join(list1)
print(new_str1) # apple
print(new_str1) # ap+p+le
list2 = [1,2,3]
new_str = '+'.join(list2)
print(new_str) # TypeError: sequence item 0: expected str instance, int found
- upper/lower/swapcase:大小寫相關(guān)
str1 = 'abc'
print(str1.upper())
print(str2) # ABC
- ljust/center/rjust/zfill:排版相關(guān) 左中右對(duì)齊
str1 = 'how are you?'
new_str0 = str1.center(20)
new_str1 = str1.center(20,"*")
new_str2 = str1.ljust(20,"*")
new_str3 = str1.rjust(20,"8")
new_str4 = str1.zfill(20) # zfill() takes exactly one argument
new_str5 = str1.rjust(20)
print(new_str0) # how are you?
print(new_str1) # ****how are you?****
print(new_str2) # how are you?********
print(new_str3) # ********how are you?
print(new_str4) # 00000000how are you?
print(new_str5) # how are you?
# 練習(xí)1: 給任意一個(gè)商品的數(shù)字編號(hào)值,轉(zhuǎn)換成固定格式的商品編碼: GDXXXX -> GD0001, GD0012,....
num = 2
num_str = 'GD'+str(num).zfill(4) # GD0002
- replace:替換子串
- 字符串1.replace(字符串2, 字符串3) - 將字符串1中所有的字符串2全部替換成字符3
- 字符串1.replace(字符串2, 字符串3, N) - 將字符串1中的前 N 個(gè)字符串2替換成字符串3
str1 = 'how are you? i am fine, Thank you!'
new_str = str1.replace('o', '*')
print(new_str) # h*w are y*u? i am fine, Thank y*u!
new_str = str1.replace('o', '+', 2)
print(new_str) # h+w are y+u? i am fine, Thank you!
new_str = str1.replace('you', 'me')
print(new_str) # how are me? i am fine, Thank me!
- find: 獲取字符串2第一次在字符串1中出現(xiàn)的位置(用正的下標(biāo)值表示),找不到返回 -1
str1 = 'How are you? - I am fine. Thank you!'
print(str1.find('you')) # 8
- count:統(tǒng)計(jì)字符串1出現(xiàn)字符串2的次數(shù)
字符串1.count(字符串2)
字符串1.count(字符串2,開始下標(biāo),結(jié)束下標(biāo))
str1 = 'how are you?'
print(str1.count('you')) # 1
print(str1.count('you',0,5)) # 0
- expandtab:
- 字符串1.expandtabs() - 將字符串中的制表符替換成8個(gè)空格
- 字符串1.expandtabs(N) - 將字符串中的制表符替換成N個(gè)空格
str2 = '\tabc\t123'
new_str2 = str2.expandtabs()
print(str2,len(str2))
print(new_str2,len(new_str2))
new_str3 = str2.expandtabs(2)
new_str4 = str2.expandtabs(3)
new_str5 = str2.expandtabs(4)
new_str6 = str2.expandtabs(5)
new_str7 = str2.expandtabs(6)
print(new_str3)
print(new_str4)
print(new_str5)
print(new_str6)
print(new_str7)
- strip 刪除空白(空白包括空格 換行等)
- str.strip():去掉字符串前后的所有空白,內(nèi)部的空白不受影響
- str.lstrip():去掉字符串前部(左部)的所有空白
- str.rstrip():去掉字符串后部(右部)的所有空白
- str.strip('*') :掉字符串前后的所有*,內(nèi)部的空白不受影響
astr = ' How are you? - I am fine. Thank you! )
astr1 = astr.strip()
astr2 = astr.lstrip()
astr3 = astr.rstrip()
print(astr1)
print(astr2)
print(astr3)
- 判斷字母數(shù)字
- str.isalpha:判斷字符串是否全部由字母構(gòu)成
- str.isdigit:判斷字符串是否全部由數(shù)字構(gòu)成
- str.isalnum:判斷字符串是否僅包含字母和數(shù)字, 而不含特殊字符
格式化輸出
格式占位符
- 包含格式占位符的字符串 % (數(shù)據(jù)1,數(shù)據(jù)2,數(shù)據(jù)3)
- 數(shù)據(jù)的個(gè)數(shù)與前面占位符的個(gè)數(shù)保持一致
- 格式占位符:
- %d 給整數(shù)站位
- %Nd / -Nd
- %f 給小數(shù)站位
- %.Nf 保留N位小數(shù)
- %s 給字符串站位
字符串中某一個(gè)或多個(gè)部分不確定就可以用格式字符串來(lái)實(shí)現(xiàn)功能
name = input('姓名:')
age = int(input('年齡:'))
salary = float(input('年薪:'))
message = '%s今年%d歲。年薪:%f元' % (name,age,salary)
message1 = '%s今年%5d歲。' % (name,age)
message2 = '%s今年%-5d歲。' % (name,age)
format
字符
在字符串中通過(guò){}來(lái)占位表示字符串中變化的部分
- {}的個(gè)數(shù)和數(shù)據(jù)項(xiàng)數(shù)量保持一致
- 列表形式的format:下標(biāo)
- key形式的format:{key}
- key形式format的變形
name = input('姓名:')
age = int(input('年齡:'))
# {}的個(gè)數(shù)和數(shù)據(jù)項(xiàng)數(shù)量保持一致
message = '{}今年{}歲。'.format(name,age)
print(message)
#列表形式的format
message1 = '你好,我是{0}。你多大了?--嗨,{0}你好,我{1}'.format(name,age)
print(message1)
# key形式的format:{key}
message2 = '我叫{name},今年{age}。'.format(name= 'ALLEN',age=18)
print(message2)
# key形式format的變形
message3 = f'那個(gè){name},已經(jīng){age}了。'
print(message3)
數(shù)字格式化
- :.Nf - 顯示小數(shù)點(diǎn)位數(shù)(N)
- :.x>Nd - 數(shù)字補(bǔ)x (填充右邊, 寬度為4)
- :.x<Nd
- :, -
- :.N% - 以百分比的形式顯示數(shù)據(jù),保留N位小數(shù)
print('數(shù)字:{:.2f}'.format(1.23785648))
print('數(shù)字:{:x>5d}'.format(32))
print('數(shù)字:{:0<5d}'.format(32))
num = 1000000
print('數(shù)字:{:,}'.format(num))
num = 0.45
print(f'{num:.2%}')