1. 程式人生 > >python基礎學習6----字符串操作

python基礎學習6----字符串操作

取字符串 isspace 默認 如果 class form 標識 三個參數 超過

一.重復輸出字符串

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(‘{name} is {age}‘.format(name=‘sfencs‘,age=19))  # 格式化輸出的另一種方式sfencs is 19
print(‘{name} is {age}‘.format_map({‘name‘:‘sfencs‘,‘age‘:19}))
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----字符串操作