1驾霜、編碼問題
Python3里面字符串在內(nèi)存中統(tǒng)一表現(xiàn)為Unicode編碼
ASCII編碼:英文字母森书,數(shù)字勒魔,一些符號奠蹬,一共127字符(全部一個(gè)字節(jié)表示)
Unicode編碼:解決出現(xiàn)亂碼的問題(全世界所有語言一些字符都包含進(jìn)來)是2-4個(gè)字節(jié)(16-32位),最少2個(gè)字節(jié)来颤,Unicode編碼是文本字符串在內(nèi)存中的內(nèi)在形式
utf-8編碼表:unicode編碼表的基礎(chǔ)上做的優(yōu)化汰扭,節(jié)省了空間(能夠用一個(gè)字節(jié)表示就用一個(gè)字節(jié),不能用1個(gè)字節(jié)就用多個(gè)字節(jié)表示)
gbk編碼:用雙字節(jié)編碼表示中文和中文符號
編碼與解碼:
s ='我是tom'
encode:把Unicode編碼轉(zhuǎn)換為字節(jié)流(bytes)
a = s.encode('utf-8')
print(a)
decode:把字節(jié)流還原為Unicode
b = a.decode('utf-8')
print(b)
2福铅、字符串常用內(nèi)置方法
將單個(gè)字符轉(zhuǎn)換為整數(shù):
ord函數(shù):print(ord('A'))
將整數(shù)轉(zhuǎn)換為單個(gè)字符:
chr函數(shù):print(chr(65))
字符串的賦值操作:
a_str ='cunyu'
字符串去空格和特殊字符
a_str = '? hello python '
lstrip:print(a_str.lstrip())?? #去左邊空格
rstrip:print(a_str.rstrip())? #去右邊空格
strip:print(a_str.rstrip())?? #去所有空格
b_str ='.hello python*'
print(b_str.lstrip('.'))?? # 去除左邊的符號
print(b_str.rstrip('*'))?? #去除右邊的符號
print(b_str.strip('.*'))? #去除所有符號
字符串的連接操作:
+:將兩個(gè)字符串進(jìn)行拼接
*:將字符串重復(fù)輸出n次
a ='hello '?? ? ????? b ='python'
print(a+b)?????? ? ? print(a*3)
hello python??????? hello hello hello
替換操作(replace):
a_str = 'my name is tom'
a_str.replace('tom', 'marry')? ?# 第一個(gè)為替換部分萝毛,第二部分為替換的內(nèi)容
查找(index,find):
a_str = 'my name is tom'
a_str.index('is')? ? ?# 查找is的索引,當(dāng)找不到時(shí)會(huì)報(bào)錯(cuò)
a_str.find('is')? ? # 查找is的索引滑黔,當(dāng)找不到時(shí)會(huì)返回-1
字符串的比較(<,<=,>,>=,==,!=): 比較的值為布爾
in:在什么里面
a_str = 'abcdef'
print('ab' in a_str)? # 判斷ab是否在a_str里面
大小寫轉(zhuǎn)換(swapcase())
print('SIndy'.swapcase())? ?# 將大寫轉(zhuǎn)換為小寫笆包,小寫轉(zhuǎn)換為大寫
首字母大寫(capitalsize()):
print('sindy'.capitalsize())
標(biāo)題化字符串(title()):
print('this is title'.title())
字符串切割(spilt):
print('my name is tom'.split(' '))? ?# 返回的是數(shù)組list[]
字符串的拼接(join):
print('+'.join(['my', 'name', 'is', 'tom']))? ? # join的參數(shù)為一個(gè)可迭代對象
對齊方式(ljust,rjust,center,zfill):
print('python'.ljust(10, '@'))? ?# 第一個(gè)參數(shù)為寬度环揽,第二個(gè)參數(shù)為當(dāng)字符串長度不夠固定的寬度時(shí)的填充方式
print('python'.rjust(10, '@'))
print('python'.zfill(20))? ?# 填充,拉伸,不夠的補(bǔ)0
print('python'.center(10, '@'))
判斷以字符開始或結(jié)束(startswith,endswith):返回布爾
print('abcdef'.startswith('ab'))
print('abcdef'.endswith('ef'))
判斷字符類型(isalnum,isalpha,isdigit,isspace,islower,issupper):
print('ab99'.isalnum())? # 數(shù)字或字符
print('abc'.isalpha())? # 全是字符
print('888'.isdigit())? # 全是數(shù)字
print(' '.isspace())? # 是否為空格
print('tom'.islower())? # 是否為小寫
print('tom'.isupper())? # 是否為大寫
統(tǒng)計(jì)某個(gè)字符或者某部分字符出現(xiàn)的次數(shù)(count):
print('abcdef'.count('bc'))