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