字串
切片序列列[開始位置下標:結束位置下標:步長]
不包含結束位置下標對應的資料, 正負整數均可;
步長是選取間隔,正負整數均可,預設步長為1。
例子
查詢name = "abcdefg"
print(name[2:5:1]) # cde
print(name[2:5]) # cde
print(name[:5]) # abcde
print(name[1:]) # bcdefg
print(name[:]) # abcdefg
print(name[::2]) # aceg
print(name[:-1]) # abcdef, 負1表示倒數第⼀乙個資料
print(name[-4:-1]) # def
print(name[::-1]) # gfedcba
所謂字串查詢方法即是查詢子串在字串中位置或出現的次數。
find():檢測某個子串是否包含在這個字串中,如果在返回這個子串開始的位置下標,否則則返回-1.
語法字串串序列列.find(⼦子串串, 開始位置下標, 結束位置下標)
注意:開始和結束位置下標可以省略,表示在整個字串序列列中查詢。
index():檢測某個⼦串是否包含在這個字串串中,如果在返回這個⼦串開始的位置下標,否則報異常。mystr = "hello world and itcast and c++and python"
print(mystr.find('and')) # 12
print(mystr.find('and', 15, 30)) # 23
print(mystr.find('ands')) # -1
字串串序列列.index(⼦子串串, 開始位置下標, 結束位置下標)
rfind(): 和find()功能相同,但查詢⽅方向為右側開始。
rindex():和index()功能相同,但查詢⽅方向為右側開始。
count():返回某個⼦子串串在字串串**現的次數
字串串序列列.count(⼦子串串, 開始位置下標, 結束位置下標)
replace():替換
字串串序列列.replace(舊⼦子串串, 新⼦子串串, 替換次數)
split()mystr = "hello world and itcast and c++ and python"
# 結果:hello world he itcast he c++ he python
print(mystr.replace('and', 'he'))
# 結果:hello world he itcast he c++ he python
print(mystr.replace('and', 'he', 10))
# 結果:hello world and itcast and c++ and python
print(mystr)
字串串序列列.split(分割字元, num)
注意:num表示的是分割字元出現的次數,即將來返回資料個數為num+1個。
join():⽤用⼀乙個字元或⼦串合併字元串,即是將多個字元串合併為⼀乙個新的字元串。mystr = "hello world and itcast and itheima and python"
# 結果:['hello world ', ' itcast ', ' c++', ' python']
print(mystr.split('and'))
# 結果:['hello world ', ' itcast ', ' c++and python']
print(mystr.split('and', 2))
# 結果:['hello', 'world', 'and', 'itcast', 'and', 'c++', 'and', 'python']
print(mystr.split(' '))
# 結果:['hello', 'world', 'and itcast and c++ and python']
print(mystr.split(' ', 2))
字元或子串.join(多字串組成的序列)
capitalize():將字串第乙個字元轉換成大寫list1 = ['chuan', 'zhi', 'bo', 'ke']
t1 = ('aa', 'b', 'cc', 'ddd')
# 結果:chuan_zhi_bo_ke
print('_'.join(list1))
# 結果:aa...b...cc...ddd
print('...'.join(t1))
title():將字元串每個單詞首字母轉換成⼤寫。
lower():將字元串中大寫轉小寫。
upper():將字串中小寫轉大寫。
strip():刪除字串兩側空⽩字元
判斷
startswith():檢查字元串是否是以指定⼦串開頭,是則返回 true,否則返回 false。如果設定開
始和結束位置下標,則在指定範圍內檢查
isalpha():如果字元串至少有⼀乙個字元並且所有字元都是字⺟母則返回 true, 否則返回 false。字串序列.startswith(⼦串, 開始位置下標, 結束位置下標)
字元串序列.endswith(⼦串, 開始位置下標, 結束位置下標)
isdigit():如果字串串只包含數字則返回 true 否則返回 false。
isalnum():如果字元串⾄至少有⼀乙個字元並且所有字元都是字母或數字則返 回 true,否則返回
false。
**isspace():**如果字串串中只包含空⽩白,則返回 true,否則返回 false。
python基礎那些事(三)
列表 資料1,資料2,資料3,資料4.查詢 1.下標 name list tom lily rose print name list 0 tom print name list 1 lily print name list 2 rose2.函式 index 返回指定資料所在位置的下標 列 表序列 i...
Python基礎 關於「迴圈」那些事
while 迴圈 泛迴圈迴圈的跳出和繼續 python中常見的迴圈有兩類 list是最常見的可迭代物件,其他可迭代的物件例如dict,set,file lines,string等 for i in set 1,2,3 print i 輸出 123 import string list num lis...
求職那些事二
在 求職那些事一 中我說過,找工作之前,首先是確定好求職目標。當定下求職目標後,接下來就是要針對目標職位撰寫乙份簡歷,借助這份簡歷向雇主推銷自己,讓雇主了解你,從而爭取獲得面試的機會。現在就讓我們來說說寫簡歷這個事。簡歷應該言簡意賅 實事求是 有的放矢。因而,在寫簡歷見之前,很有必要了解目標職位的工...