1. 程式人生 > 實用技巧 >【Python】基礎-字串的常用方法

【Python】基礎-字串的常用方法

str.strip()  刪除字串兩邊的指定字元,預設為空格

str1 = '    python  '
str2 = str1.strip()

  

str.lstrip()  刪除字串左邊的指定字元,括號內寫入指定字元,預設空格

str.rstrip()  刪除字串右邊的指定字元,括號內寫入指定字元,預設空格

str1 = '    python    '
str2 = str1.lstrip()
str3 = str1.rstrip()
print(str2,str3)

  

複製字串

str1 = '    python    '
str2 = str1
print(str1)

  

連線字串,可以使用 + 號或者使用str.join來連線2個字串,

str1 = 'hello'
str2 = 'world'
print(str1+str2)

  

str1 = ['hello','world']
str2 = '_'.join(str1)
print(str2)

#請將下面列表中的每個元素用 - 連線起來
username = ['海綿寶寶','派大星','章魚哥']
print("-".join(username))

  

查詢字串,str.index 和 str.find 功能相同,區別在於 find() 查詢失敗會返回 -1,不會影響程式執行,一般用 find!=-1 或者 find > -1 來判斷條件。

str1 = 'hello world'
print(str1.index("e"))
print(str1.index("x"))  #使用index查詢字串不存在的字元,會報錯
print(str1.find("e"))
print(str1.find("x"))

  

是否包含指定字串,

str1 = "hello world"

str2 = "hello" in str1
print(str2)

str3 = '123' not in str1
print(str3)

  

計算字串的長度

str1 = "hello world"

print(len(str1))

  

字串中的字母大小寫轉換

str1 = "Hello World"

#轉化為小寫
print(str1.lower())

#轉化為大寫
print(str1.upper())

#大小寫互換
print(str1.swapcase())

#首字母大寫
print(str1.capitalize())

#把每個單詞的第一個字母轉化為大寫,其餘小寫 
print(str1.title())

  

將字串放入中心位置,可以指定長度以及位置兩邊字元

str1 = "python"
print(str1.center(40,"*"))

  

字串統計

str1 = "python"
print(str1.count("y"))