Python基礎:字符串操做

#字符串類型的生成
name = '小明' nums = str(9) print(name,'******',nums) #字符串的基本操做
 words = 'diFfrEnCe'
#根據索引獲取值
print(words[1]) #切片
print(words[1:4]) #帶步進值的切片
print(words[0:4:2]) #遍歷字符串 # for item in words: # print(item)

#swapcase 大小寫互轉
print(words.swapcase()) #upper 全大寫
print(words.upper()) #lower 全小寫
print(words.lower()) #capitalize 第一個字母大寫
print(words.capitalize()) #title 單詞首字母大寫
print('hello world'.title()) #find 查找值定字符第一次出現的位置,找到返回索引,找不到返回-1(順序查找.可指定範圍) #res = words.find('e')
res = words.find('g') print(res) #rfind 查找值定字符第一次出現的位置,找到返回索引,找不到返回-1(逆序查找,可指定範圍)
res = words.rfind('e') print(res) #len 獲取字符串長度
print(len(words)) #count 指定字符出現的次數(可給範圍)
res = words.lower().count('f',3,8) print(res) #index與find相似,找不到返回ValueError: substring not found # res = words.index('g') # print(res)

#startwith 檢測字符串是否以值定字符開頭,返回布爾值
res = words.startswith('diff') print(res) #endwith 檢測字符串是否以指定字符結束
res = words.endswith('hh') print(res) #isupper 檢測字符串是否有大寫字母組成
res = words.isupper() print(res) res = words.upper().isupper() print(res) #islower 檢測字符串是否有小寫字母組成

#istitle 檢測字符串是否符合首字母大寫

#isalnum 檢測字符串由數字、字母(漢字及其餘文字)組成

#isalpha 檢測字符串是否由字母和文字組成

#isnumeric 檢測字符串是否由數字組成

#isdecimal 檢測字符串是否由數字組成

#isspace 檢測字符串是否由空白字符組成

#split 使用指定字符切割字符串,返回列表
words = 'life is short , you need python' res = words.split(' ') print(res) #splitlines 使用換行符切割字符串
res = words.splitlines() print(res) #join() 將容器數據使用值定字符鏈接成一個字符串
words = ['life', 'is', 'short', ',', 'you', 'need', 'python'] res = '\r\n'.join(words) print(res) #zfill 零填充
words = '1234567' res = words.zfill(9) print(res) #center 使用指定字符填充字符串,原有內容居中顯示
words = 'python' res = words.center(10,'*') print(res) #ljust 使用指定字符填充字符串,原有內容居左顯示
words = 'python' res = words.ljust(10,'*') print(res) #rjust 使用指定字符填充字符串,原有內容居右顯示
words = 'python' res = words.rjust(10,'*') print(res) #strip 去掉字符左右兩側指定的字符,默認去點空格
words = '**python**' resj = words.strip('*') print(resj) #lstrip 去掉字符左側指定的字符,默認去點空格
words = '**python**' resj = words.lstrip('*') print(resj) #rstrip 去掉字符右側指定的字符,默認去點空格
words = '**python**' resj = words.rstrip('*') print(resj) #maketrans() 製做轉換字典(只能單個字符)
trans_dict = ''.maketrans({ 'a':'85-100', 'b':'70-85', 'c':'60-70', 'd':'0-60' }) print(trans_dict) #translate() 替換字符串操做
word = '小明a小紅b小張c小fd' res = word.translate(trans_dict) print(res)
相關文章
相關標籤/搜索