1. 程式人生 > >pyhton3資料型別之str

pyhton3資料型別之str

一、python中的字串

1、定義字串:可以通過單引號和雙引號來建立字串,兩種方式的作用和效果一樣
s1 = 'hello world' 一個單引號
s2 = "hello world"
其他:
s3 = '''hello world''' 三個單引號
s4 = """hello world"""三個雙引號
這兩種通常用於換行,同換行符\n一樣

2、單個字元也是一個字串

3、字串支援索引,從字串頭開始的索引是0,從字串結尾開始的索引是-1

獲取單個字元:s1[3] 結果為‘l‘
擷取字串:s1[3:6] 結果為‘lo ‘
擷取前n個字元:s1[:3]結果為‘hel‘

二、python轉義字元

轉義字元 描述
\(在行尾時) 續行符
\\ 反斜槓符號
\’ 單引號
\” 雙引號
\a 響鈴(半形空格)
\b 退格(Backspace,刪除\b前的一個空格)
\000
\n 換行
\v 縱向製表符
\t 橫向製表符
\r 回車
\f 換頁

三、python字串運算子

a=’Hello’ b=’World’

操作符 描述 例項
+ 字串連線 a + b 輸出結果: HelloWorld
* 重複輸出字串 a*2 輸出結果:HelloHello
[] 通過索引獲取字串中字元 a[1] 輸出結果 e,a[-1]的結果 o
[ : ] 擷取字串中的一部分 a[1:4] 輸出結果 ell,a[:-1]的結果 Hell
in 成員運算子 如果字串中包含給定的字元返回 True ‘H’ in a 輸出結果 True
not in 成員運算子 如果字串中不包含給定的字元返回 True,’s’ not in a 輸出結果 False
r/R 原始字串 字串前加上r/R,那麼字串中的轉義都不會起作用

四、python字串格式化

python字串格式化符號:

符號 描述
%c 格式化字元及其ASCII碼
%s 格式化字串
%d 格式化整數
%u 格式化無符號整型
%o 格式化無符號八進位制數
%x 格式化無符號十六進位制數
%X 格式化無符號十六進位制數(大寫)
%f 格式化浮點數字,可指定小數點後的精度
%e 用科學計數法格式化浮點數
%E 作用同%e,用科學計數法格式化浮點數
%g %f和%e的簡寫
%G %f 和 %E 的簡寫
%p 用十六進位制數格式化變數的地址

五、python字串內建函式

注意:python字串內建函式大多數是對c語言string的封裝,所以使用時不能帶引數名稱
s1 = ‘Hello {0} {1} ’
s2 = ‘World’
s3 = ‘!’
引數前*表示一個或多個引數,**表示一個或多個鍵值對引數,=表示有預設值,無符號表示必須引數,下表中省略self

函式 描述 引數說明
format(*args, **kwargs) 格式化字串 引數列表長度必須和佔位符數量相等
strip(chars=None) 去掉字串兩端指定的字元,預設去除空格 chars型別是None或者str
split(sep=None, maxsplit=-1) 分割字串 sep為分割符,maxsplit最大分割數,返回結果為list
replace(old, new, count=None) old為需要被替換的字元,new為新的字串,count為替換個數,預設替換所有 count為0時不替換任何字元
find(sub, start=None, end=None) 查詢指定字串sub在原字串中的位置 start為查詢的起始位置,end為查詢的終止位置,未查到返回-1,查到返回sub在字串中的索引
capitalize() 將字串的首字母轉換為大寫
casefold() 將字串中的所有大寫轉換為小寫
center(width, fillchar=None) 將字串兩邊用fillchar字元填充 width填充後總的長度
count(sub, start=None, end=None) 統計字串的個數 sub被統計的字串,start開始統計的起始位置,end為統計的結束位置
encode(encoding=’utf-8’, errors=’strict’) 對字串進行編碼 預設編碼方式是utf-8,預設的錯誤處理方式是strict。返回byte陣列
endswith(suffix, start=None, end=None) 判處字串的是否是以suffix結尾 start開始位置,end結束位置
expandtabs(tabsize=8) 將字串中的\t轉換為指定哥數空格 預設8個空格
index(sub, start=None, end=None) 和find方法一樣,只不過沒有查到會丟擲異常
isalnum() 如果字串是由數字、字元或者漢子組成,則返回True,否則返回False
isalpha() 如果字串是由數字、字元或者漢子中的一種組成,返回True否則返回False
isdecimal() 如果字串中只有十進位制數字字元,則返回True,否則返回False
isdigit() 如果字串中所有字元都是十進位制數字,則返回True,否則返回False ‘¹①⒈ ‘等特殊符號組成字元字串返回True
isnumeric() 如果字串中所有字元都能代表一個數字,則返回True,否則返回False ¾௰Ⅹ六’等特殊符號組成字元字串返回True
islower() 判斷字串的每個字元是否都是小寫 至少帶有一個英文字元並且字元是小寫才返回True,其他全返回False
isidentifier() 判斷一個字串是否可以作為識別符號 如果字串是關鍵字,也會返回True
isprintable() 是否是可列印字元,也就是可見字元 ASCII字符集由95個可列印字元(0x20-0x7E)和33個控制字元(0x00-0x19,0x7F)組成、
isspace() 是否是空白字元 常見的有‘\t\r\n\v\f‘已經全形空格和 半形空格
istitle() 字串中所有單詞首字母是否是大寫
isupper() 字串的每個單詞是否是大寫
join(iterable) 在可迭代的元素中插入字串 迭代的元素必須是字串
ljust 返回一個原字串左對齊,並使用 fillchar 填充至長度 width 的新字串,fillchar 預設為空格
lower() 將字串中的大寫全部轉換為小寫
lstrip(chars=None) 移除字串最左邊指定的字元 預設去掉空格
maketrans( *args, **kwargs) 將兩個字串轉化為對應ASCII碼字典 str.maketrans(‘god’,’123’)的結果是{103: 49, 111: 50, 100: 51}
translate(table) 更具一個字典來轉換字元 table為字元ASCII碼字典,例如{103: 49, 111: 50, 100: 51}表示的是{‘g’: ‘o’, ‘d’: ‘1’, ‘2’: ‘3’}
partition(sep) 從左邊第一個分割符分割字串 分割字串為sep,返回list中包含分割符
rfind(sub, start=None, end=None) 從字串的右邊查詢字串 相當於find,只不過,返回的index從最右邊開始計算的
rpartition(sep) 從右邊第一個分割符分割字元竄 分割字串為sep,返回list
rsplit(sep=None, maxsplit=-1) 和split相似,用於分割字串 和split區別在於maxsplit是從右開始計數的
swapcase() 將字串中的小寫全部轉換大寫
title() 將字串中的每個單詞的首字母大寫
zfill(width) 在字串的左邊新增0使得字串的長度為width

測試程式碼:

if __name__ == '__main__':
    s1 = 'Hello {0} {1} '
    s2 = 'World'
    s3 = '!'
    print(len(s1))
    print(s1.format(s2,s3))
    print(s2.strip(''))
    print(s1.split(' '))
    print(s1.replace('l','s',2))
    print(s1.find('{',7,9))
    print('world'.capitalize())
    print("WORld S".casefold())
    print(s2.center(12,'s'))
    print(s1.count('l',1,3))

    s4 = '學\t習'
    print(s4.encode('gbk'))
    print(s2.endswith('l',1,4))
    print(s4.expandtabs())
    print(s2.index('o'))
    print('hi你好123'.isalnum())
    print('你好'.isalpha())
    print('1'.isdecimal())
    print('¹①⒈'.isdigit())
    print('¾௰Ⅹ六'.isnumeric())
    print('[email protected]學'.islower())
    print('_jwr_0_'.isidentifier())
    print('None'.isidentifier())
    print('\t'.isprintable())
    print('\t\r\n\v\f'.isspace())
    print('Hello World'.istitle())
    print('HELLO WORLD'.isupper())
    myArray = {'1','2','3','3'}
    print('HELLO WORLD'.join(myArray.__iter__()))
    print('Hello World'.ljust(15,'c'))
    print('Hello WORLd'.lower())
    print('Hello WORLdH'.lstrip('H'))

    a = 'good good study'
    print(a.translate(str.maketrans('god','123')))
    print(a.translate({103: 49, 111: 50, 100: 51}))
    print(a.partition('oo'))
    print(a.rfind('o'))
    print(a.rpartition('oo'))
    print(a.rsplit('oo',1))
    print(a.split('oo',1))
    print(a.swapcase())
    print(a.title())
    print(a.zfill(44))

結果:

14
Hello World ! 
World
['Hello', '{0}', '{1}', '']
Hesso {0} {1} 
-1
World
world s
sssWorldssss
1
b'\xd1\xa7\t\xcf\xb0'
True
學       習
1
True
True
True
True
True
True
True
True
False
True
True
True
3HELLO WORLD2HELLO WORLD1
Hello Worldcccc
hello world
ello WORLdH
1223 1223 stu3y
1223 1223 stu3y
('g', 'oo', 'd good study')
7
('good g', 'oo', 'd study')
['good g', 'd study']
['g', 'd good study']
GOOD GOOD STUDY
Good Good Study
00000000000000000000000000000good good study