1. 程式人生 > 實用技巧 >字串及字串的常用方法

字串及字串的常用方法

str(不可變物件)

字串的定義(不區分單引號和雙引號)
  str1 = "HelloWorld"
  str2 = 'HelloWorld'

字串的輸入
  str = input("從鍵盤任意錄入一個字串:")

字串求長度
長度 = len(變數/常量)

字串的索引值
範圍:[0,len(變數)-1]
# 使用迴圈完成字串中每個字串的列印,使用\t隔開
str = "Hello"
# 1.while迴圈
i = 0
length = len(str)
print("使用while迴圈進行字串列印:")
while i < length:
    print(str[i],end="
\t") i += 1 # 2.for迴圈 print("\n第一種使用for迴圈進行字串列印:") for i in range(length): print(str[i], end="\t") print("\n第二種使用for迴圈進行字串列印:") for i in str: print(i, end="\t")

操作字串常用的方法

1.字串的切片操作


    字串變數名[start:end:step]
不包含end

注意:切片操作不會報越界異常 IndexError
str_num = "0123456789"
# 從開始位置擷取兩個字元出來
result = str_num[0:2] print("從字串\"{0}\"開始位置擷取兩個字元出來:{1}".format(str_num,result)) # 從開始位置為1的地方,擷取八個字元出來,並設定步長為2 result2 = str_num[1:9:2] print("從字串\"{0}\"開始位置為1的地方,擷取八個字元出來,並設定步長為2:{1}".format(str_num,result2)) # step為負值,表示從右往左取(如果要指定開頭和結尾,開頭的值要大,結尾的值要小) result3 = str_num[::-1] print("將字串\"{0}\"倒序輸出:{1}
".format(str_num,result3))

2.find/rfind

如果有返回索引值,沒有則返回-1
str1 = "good good study,day day up"
str2 = "you can you up,no can no b b"

# find從左往右找
print(str2.find("no"))
# rfind從右往左找
print(str2.rfind("no"))

3.index/rindex

跟find()方法一樣,如果有返回索引值,只不過沒有找到的話會報一個異常 raise ValueError
str1 = "good good study,day day up"
str2 = "you can you up,no can no b b"

# 索引值index跟find類似,從左往右尋找索引值
print(str2.index("no"))
# # 跟find類似,從右往左找索引值
print(str2.rindex("no"))

4.count

返回str在目標字串中start-end之間出現的次數,如果有返回出現的次數,沒有則返回0
str1 = "good good study,day day up"
str2 = "you can you up,no can no b b"

# count統計字串出現的次數
print(str2.count("no"))

5.replace

修改字串中的指定字元
(注意:replace不是對原字串str2進行替換,而是將替換完之後的值儲存到新的地方)
str1 = "good good study,day day up"
str2 = "you can you up,no can no b b"

str3 = str2.replace("you","YOU")
# 注意:replace不是對原字串str2進行替換,而是將替換完之後的值儲存到新的地方
print("id:{0}\tstr2 = {1}".format(id(str2),str2))
print("id:{0}\tstr3 = {1}".format(id(str3),str3))

# 只對第一個can進行替換
str3_1 = str2.replace("can","CAN",1)
print("id:{0}\tstr3_1 = {1}".format(id(str3_1),str3_1))

6.split

以指定分隔符,對字串進行拆分(拆分好的字串,以list型別進行儲存)


str1 = "good good study,day day up"
str2 = "you can you up,no can no b b"

# split以指定分隔符空格,對字串進行拆分,並且將拆分好的字串,以list型別進行儲存
str4 = str2.split(" ")
print("str4 的資料型別:",type(str4))
print("str4 = ",str4)

7.capitalize

把字串的第一個字元大寫
str1 = "good good study,day day up"
str2 = "you can you up,no can no b b"

# capitalize將字串首字母大寫
str5 = str2.capitalize()
print("str5 = ",str5)

8.titile


將所有單詞的首字母大寫
str = "you can you up,no can no b b"

# title將所有單詞的首字母大寫
str1 = str.title()
print("str1 = ",str1)

9.upper 和 lower


upper
轉換字串中的所有的小寫字元為大寫
lower
轉換字串中所有的大寫字元為小寫
str = "you can you up,no can no b b"

# upper()小寫字元轉化為大寫
str2 = str.upper()
print("將所有小寫字元轉化為大寫\tstr2 = ",str2)

# lower()大寫字元轉化為小寫
str3 = str2.lower()
print("將所有大寫字元轉化為小寫\tstr3 = ",str3)

10.startswith 和 endswith

stratswith
判斷字串以什麼開頭,返回值為bool值

endswith
判斷單詞以什麼結尾,返回值為bool值
# startswith()判斷字串以什麼開頭,返回值為bool值
url1 = "https://www.baidu.com/"
# 判斷字串是否以"https://www"開頭
if url1.startswith("https://www"):
    print("{}\t該網址為有效網址!".format(url1))
else:
    print("{}\t該網址為無效網址,請重新輸入...".format(url1))

# endswith()判斷字串以什麼結尾,返回值為bool值
fileName = "Test.py"
# 判斷字串是否以".py結尾
if fileName.endswith(".py"):
    print("{}\t該檔案為python檔案!".format(fileName))
else:
    print("{}\t該檔案不是python檔案...".format(fileName))

11.isalpha 、 isdigit 和 isalnum

isalpha
判斷目標字串中是否所有的字元都為字母,返回True,或者False

isdigit
判斷目標字串中是否所有的字元都為數字,返回True,或者False

isalnum
 判斷目標字串是否所有的字元都為字母和數字組合,返回True,或者False
num_input = input("請輸入一個字串:")

if num_input.isalpha():
    print("該字串都為字母組合...")
elif num_input.isdigit():
    print("該字串都為數字組合...")
elif num_input.isalnum():
    print("該字串為字母和數字組合...")
else:
    print("該字串為其他組合...")

12.ljust(),rjust(),center()

字串對齊,剩下的以"指定字元"填充
(不寫則預設以空格進行填充)
str1 = "馬鈴薯"
print(str1)
# ljust字串居左對齊,剩下的以"*"填充
print("字串居左對齊:",str1.ljust(10,"*"))
# rjust字串居右對齊,剩下的以"*"填充
print("字串居右對齊:",str1.rjust(10,"*"))
# center字串居中對齊,剩下的以"*"填充
print("字串居中對齊:",str1.center(10,"*"))

13.lstrip(),rstrip(),strip()

 刪除字串中的空格



str1 = "        tyy        "
print(str1)
print("刪除字串左邊的空格:",str1.lstrip())
print("刪除字串右邊的空格:",str1.rstrip())
print("刪除字串兩邊的空格:",str1.strip())