python基礎學習6 字串操作

2022-05-15 19:49:04 字數 2386 閱讀 6765

一.重複輸出字串

print('hello'*20)#輸出20個hello

二.通過索引獲取字串中字元

print('helloworld'[2:])#輸出lloworld

三.關鍵字 in

print('ll' in 'hello')#輸出true

四.格式化輸出

print('darling,i love you')

print('%s,i love you'%'darling')

五.字串的連線

a='123'

b='abc'

d='44'

c= ''.join([a,b,d])

print(c)#輸出123abc44

c= '*'.join([a,b,d])

print(c)#輸出123*abc*44

六.字串的內建方法

str='darling,i love you'

print(str.count('l')) # 統計元素'l'的個數

print(str.capitalize()) # 只有首字母大寫

print(str.center(50,'#')) # 居中###############darling,i love you################

print(str.endswith('you')) # 判斷是否以某個內容結尾

print(str.startswith('darling')) # 判斷是否以某個內容開頭,此處輸出false

print(str.find('i')) # 查詢到第乙個元素,並將索引值返回,如果沒有該元素輸出-1

print(str.index('a'))#查詢到第乙個元素,並將索引值返回,如果沒有該元素則報錯

print(' is '.format(name='sfencs',age=19)) # 格式化輸出的另一種方式sfencs is 19

print(' is '.format_map())

print('dar\tling,i love you'.expandtabs(tabsize=20))#製表符的長度為20

print('asd'.isalnum())#檢測字串是否由字母和數字組成

print('12632178'.isdecimal())#檢查字串是否只包含十進位制字元

print('1269999'.isnumeric())#檢測字串是否只由數字組成

print('abc'.isidentifier())#判斷是否滿足識別符號定義規則。只能是字母或下劃線開頭、不能包含除數字、字母和下劃線以外的任意字元。

print('abc'.islower())#檢測字串是否全由小寫字母組成

print('abc'.isupper())#檢測字串是否全由大寫字母組成

print(' e'.isspace())#檢測字串是否只由空格組成

print('my title'.istitle())#檢測字串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫

print('my title'.lower())#轉換字串中所有大寫字元為小寫

print('my title'.upper())#轉換字串中所有小寫字元為大寫

print('my title'.swapcase())#對字串的大小寫字母進行轉換

print('my title'.ljust(10,'*'))#返回乙個原字串左對齊,並使用空格填充至指定長度的新字串my title**

print('my title'.rjust(10,'*'))#返回乙個原字串右對齊,並使用空格填充至指定長度的新字串**my title

print('\tmy tltle\n'.strip())#用於移除字串頭尾指定的字元(預設為空格或換行符)或字串行

print('\tmy tltle\n'.lstrip())#用於截掉字串左邊的空格或指定字元

print('\tmy tltle\n'.rstrip())#用於截掉字串右邊的空格或指定字元

print('my title title'.replace('title','new',1))#把字串中的 old(舊字串) 替換成 new(新字串),如果指定第三個引數max,則替換不超過 max 次。

print('my title title'.rfind('t'))#從右向左尋找第乙個t的索引

print('my title title'.split('i',1))#通過指定分隔符對字串進行切片,數字引數為分割的次數,不填為全分割

print('my title title'.title())#返回'標題化'的字串,即所有單詞都是以大寫開始,其餘字母均為小寫

Python基礎 6 字串定義與操作

n 換行注釋可表示多行資訊輸出 t製表 print內三層注釋用於表示多行資訊輸出 print 566 n 換行注釋可表示多行資訊輸出 t製表 print內三層注釋用於表示多行資訊輸出 print asd fgh mm print asd fgh n mm print asd fgh t mm asd...

Python基礎4 字串

python字串是由數字 字母 下劃線組成的一串字元,我們可以使用引號來建立字串。如 str helloworld 在python中沒有char型別,單個字元也作為string使用 python的字串列表有2種取值順序 a.自左向右,預設索引從0開始,索引長度最長為字串長度 1 b.自右向左,預設索...

Python基礎 七 字串

python字串 python 訪問字串中的值 python 不支援單字元型別,單字元在 python 中也是作為乙個字串使用。python 訪問子字串,可以使用方括號來擷取字串,如下例項 var1 hello world var2 runoob print var1 0 var1 0 print ...