1. 程式人生 > >python基礎資料型別:str(字串)__003

python基礎資料型別:str(字串)__003

1、str(字串):python3中凡是引號括起來的都是字串(包括單引號'字串內容',雙引號"字串內容")

2、字串的索引和切片

(1)索引

s = 'sdflajdf1212'

print(s[0])  #擷取字串s的第一個元素s

print(s[-1]) #擷取字串s的最後一個元素2

print(s[3])  #擷取字串s的第四個元素l

(2)切片

s = 'aslfja121lj'

print(s[0:3])  #擷取字串s的元素asl

print(s[:])    #擷取字串s的所有元素

#s[首:尾:步長]

print(s[-1::-1])  #倒著擷取字串s的元素jl121ajflsa  切片取字串,反向,步長為1

print(s[-1:3:-1])  #倒著擷取字串s的元素jl121aj   切片取字串,反向,步長為1

print(s[-1:3:-2])  #倒著擷取字串s的元素j11j  切片取字串,反向,步長為2

print(s[::-1])  #  切片取字串所有元素,反向,步長為2

3、字串的操作方法

(1)方法:capitalize()  #字串中第一個是字母大寫,其餘的字母小寫

s = 'aslfj a121lj'
print(s.capitalize())   # Aslfj a121lj

(2)方法:upper() 字串全部大寫;lower() 字串全部小寫;title() 字串每個單詞的首字母大寫

s = 'aslfj a121lj'
print(s.title())  #Aslfj A121Lj
print(s.upper())  #ASLFJ A121LJ
print(s.lower())  #aslfj a121lj

    應用場景例子:驗證碼不區分大小寫

while 1:
    you_input = input('請輸入驗證碼:')
    if you_input.lower() == 'acd2':
        print('驗證碼輸入正確')
        break
    else:
        print('驗證碼輸入錯誤,請重新輸入')

(3)方法:swapcase()  大小寫反轉

s = 'Aslfj a121lj'
print(s.swapcase())  #aSLFJ A121LJ

(4)方法:center(int,'填充內容')  #居中空白填充,int是填充寬度

s = 'aasdSDS adsds'
s6 = s.center(30,"T")
print(s6)  #TTTTTTTTaasdSDS adsdsTTTTTTTTT

(5)公共方法:(包括列表、元組和字典),檢視字串的長度

i = "asdljf ssdlfj"
j = len(i)
print(j)   # 13

(6)方法:startswitch() 用於檢查字串是否以指定字串開頭,如果是則返回True,否則返回False;如果指定start和end指定值,則指定範圍內檢查。

格式:S.startswith(prefix[,start=0[,end=len(S)]])

S - - 父字串。

prefix - - 指定字首,該引數可以是一個字串或者是一個元素。

start - - 可選引數,字串中的開始位置索引,預設為0。(可單獨指定)

end - - 可選引數,字元中結束位置索引,預設為字串的長度。(不能單獨指定)

S = "this is string example....wow!!!"
print (S.startswith( 'this' ))            #True 
print (S.startswith( 'string', 8 ))       #True
print (S.startswith( 'this', 0,len(S) ))  #True

(7)find和index

find 通過元素找索引,找不到返回-1,所以用find

index通過元素找索引,找不到報錯

S = " this is string example....wow!!! "
print(S.find(','))
print(S.index(','))

#E:\python\python.exe E:/wj/python_practice/複習1.py
# -1
# Traceback (most recent call last):
#   File "E:/wj/python_practice/複習1.py", line 432, in <module>
#     print(S.index(','))
# ValueError: substring not found

(8)strip:預設刪除字串兩端的空格;lstrip:刪除字串左邊的空格;rstrip:刪除字串右邊的空格。

S = " this is string example....wow!!! "
print(S.strip())
#this is string example....wow!!!

(9)count() 方法用於統計字串裡某個字元出現的次數。可選引數為在字串搜尋的開始與結束位置

格式:str.count(sub, start= 0,end=len(string))

 sub - - 搜尋的子字串

start - - 字串開始搜尋的位置。預設為第一個字元, 第一個字元索引值為0。

end - - 字串中結束搜尋的位置。字元中第一個字元的索引為0。預設為字串的最後一個位置。

S = " this is string example....wow!!! "
s1 = S.count('s',5,8)
print(s1)  #1

(10)字串型別格式化輸出:

%佔位符,s字串,d:digit數字(注:只是單純加%:%%)

name = input('請輸入姓名:')
age = input('請輸入年齡:')
height = input('請輸入身高:')
msg = '我叫%s,我年齡是%s,我的身高%s'%(name,age,height)
print(msg)

# 請輸入姓名:江河
# 請輸入年齡:18
# 請輸入身高:170
# 我叫江河,我年齡是18,我的身高170
#使用者登入(三次輸錯機會)且每次輸錯誤時顯示剩餘錯誤次數(提示:使用格式化輸出)
count = 3
count_0 = 0
while count_0<3:
    username = input('請輸入姓名:')
    password = input('請輸入密碼:')
    if username == '江河' and password == '123456':
        print('登入成功')
    else:
        count_0 += 1
        count -= 1
        print('使用者名稱或密碼輸入錯誤,剩餘錯誤次數%s次。'%count)

format()方法,基本格式是:<模板字串{}>.format(<逗號分隔的引數>)

#(1)通過呼叫format()方法,來實現新的字串
s = "我的名字叫{},今年{},愛好{}".format('江河','18歲','爬山')
print(s)

#(2){}中錄入元素,可以指定多個相同的元素,引數只需傳入一個
s = "我的名字叫{0},今年{1},愛好{2},我叫{0}".format('江河','18歲','爬山')
print(s)

#(3)使用字典的鍵值對來做引數,無需指定引數順序
s = "我的名字叫{name},今年{age},愛好{hobby},我叫{name}".format(name = '江河',hobby = '爬山',age = '18歲')
print(s)


#(4)引用引數
name = input('請輸入名字: ')
s = "我的名字叫{name_1},今年{age},愛好{hobby},我叫{name_1}".format(name_1= name,hobby = '爬山',age = '18歲')
print(s)

(11)replace()用於修改字串中的old(舊的字串)替換成new(新字串),如果指定第三個引數max,則替換不超過max次。

格式:replace(self,old,new,count= None)  old:要代替的內容,new:新的內容,count:內容如果有重複的,代替幾個

s = "來看待街坊鄰居複合大師鄰居鄰居客戶"
print(s.replace('鄰居','江河',2))

#來看待街坊江河複合大師江河鄰居客戶

(12)isdigit()判斷字串是否由純數字組成

s = "12345"
print(s.isdigit())  #True

#加法計算
#加法計算
sum = 0
count = input('請輸入運算的資訊:')
for i in count.split('+'):
    sum += int(i)
print(sum)

# 計算任意輸入的字串,包含多少個數字
count = 0
s = input("請輸入資訊:")
for i in s:
    if i.isdigit():
        count += 1
print(count)