字符串常用方法
- str.upper():將字符串中字符轉換爲大寫。返回新字符串
- str.lower():將字符串中字符轉換爲小寫。返回新字符串
- str.startswith(s1):判斷字符串str是否以字符串s1開頭,返回bool
- str.endswith(s1):判斷字符串str是否以字符串s1結尾,返回bool
- str.split(s1):將字符串str以s1爲分隔符分隔,返回一個列表
- str.count(s1):統計str中s1出現的次數。返回int
- str.replace(old,new):將字符串str中的old字符串全部替換成new。返回字符串
- str.center(width, [s1]):將字符串擴展到長度爲width,原字符串居中,不足就以字符s1填補(注意不是s1只能是單個字符,即char)。s1可選。返回新字符串
- str.strip(s1):去除字符串str兩端的s1字符。返回新字符串
- str.join(iter):在生成器iter裏的所有元素後都加上字符串str1,再拼接。最終返回一個字符串。
實例
str1 = "asd"
str2 = "ASDqwe"
print str1.upper() # 輸出字符串的大寫形式 ASD
print str2.lower() # 輸出字符串的小寫形式 asdqwe
print str1.startswith("as") # 輸出True。 判斷str1是否是以字符串"as"開頭。這裏"as"也可以
print str1.endswith("sd") # 輸出True。判斷是否以字符串"sd"結尾
print str1[0] == "a" # 效果和startswith相同 True
print str1[-1] == "d" # 效果和endswith相同 True
print str1.split(",") # 輸出["asd"],這裏沒有“,”,就直接整體分割
print str1.split("s") # 輸出["a", "d"]。根據"s"進行分割
print str1.count("a") # 輸出子串"a"在字符串str1中出現的次數
print str1.replace("a", "s") # 輸出ssd。返回新字符串。將a替換成s
print str1.center(10, "*") # 輸出 ***asd**** 。
print str1.strip("a") # 去除字符串頭部和尾部的字符串"a"並返回一個新字符串
print str1.join([str1,str2]) # 輸出 asd asd ASDqwe。 注意輸出沒有空格,第一個asd是列表中的str1.第二個asd是join前的str1,ASDqwe就是列表中的str2