python字串物件和切片操作

2021-09-27 03:11:47 字數 1252 閱讀 5510

python切片,字串的逆序

#encoding=utf-8

name = 「abcdefghijklmn」

age = 20

print("%s的年齡為%d"%(name,age)) #abcdefghijklmn的年齡為20

print(「我的年齡為%d」%age) #我的年齡為20

print(name[2:-2]) #輸出為cdefghijkl

print(name[2:]) #輸出為cdefghijklmn

print(name[2:-2:2]) #輸出為cegik(第乙個2為起始位置,第二個-2為終止位置,第三個2為步長,不寫預設步長為1)

print(name[-2:]) #輸出為mn

print(name[::-1]) #輸出為nmlkjihgfedcba,對乙個字串進行逆序

字串的基本操作

mystr = 「hello world!」

print(mystr.find(「world」)) #輸出為6,在原字串中第一次出現位置的下標

print(mystr.find(「shihao」)) #輸出為-1,無法找到輸出-1

print(mystr.rfind(「itcast」)) #輸出為23, rfind為從後向前查詢

print(mystr.count(「itcast」)) #輸出為2,查詢itcast的個數

print(mystr.replace(「world」,「world」)) #輸出為hello world itcast and itcast***cpp!, 不會改變原來的字串

print(mystr.replace(「itcast」,「itcast」)) #輸出為hello world itcast and itcast***cpp!, 預設替換所有

print(mystr.replace(「itcast」,「itcast」,1)) #輸出為hello world itcast and itcast***cpp!, 1為替換一次

print(mystr.split(" ")) #輸出為[『hello』, 『world』, 『itcast』, 『and』, 『itcast***cpp!』], 以空格切割,結果為乙個列表

用函式判斷是否為質數:

python字串物件和切片操作

一 字串物件 被引號引住的內容叫子符串,有單引 雙引 三引。ss.capitalize 讓字串首字母大寫 2.ss.center 50 居中,並且還可以補充。ss.center 50,3.ss.count 統計字串 字元出現的次數 4 ss.encode 通過引數指定編碼,將指定字串轉化為位元組,編...

python 字串物件及切片

什麼是字串 肉眼可以識別具有特殊含義的字元組成的串 python如何表示字串 1 弱資料型別語言決定的,使用引號 單引號 雙引號 三引號 2 使用str s1 a s2 b s str abc 3.字串的常用方法 python提供用來切割可迭代物件 容器 字串 iterable start 從sta...

字串物件和切片操作

1 字串 被引號 單引號,雙引號,三引號 引住的內容叫做字串。字串是python中最常用的資料型別。字串常用方法 capitalize 讓字串首字母大寫 center 讓字串劇中,第二個預設是以空格填充,也可以由自己來確定填充字元 ljust 左對齊 count 右對齊 encode 通過引數指定編...