我们用下面这个字符串来做测试
testStr = "ZhanSan"
1、__cantains__
# 判断字符串是否包含某个子串,包含则返回true,不包含则返回false
print(testStr.__contains__("a"))
print(testStr.__contains__("x"))
2、capitailize
# 字符串的首字符大写 print(testStr.capitalize())
3、center,ljust,rjust
# 填充字符串,把字符串放在中间 print(testStr.center(10,"_")) # 填充字符串,把字符串放在左边 print(testStr.ljust(14,"_")) # ZhanSan_______ # 填充字符串,把字符串放在右边 print(testStr.rjust(14,"_")) # _______ZhanSan
4、count
# 统计子串在字符串中出现的次数
print(testStr.count("a"))
5、endwith,startwith
# 判断字符串是否已某个子串结尾
print(testStr.endswith("z"))
# 判断字符串是否已某个子串开头
print(testStr.startswith("z"))
6、find
# 在字符串中查找某个字符串,只返回第一个查到的字符串,存在返回子串的索引,不存在返回-1
print(testStr.find("a"))
print(testStr.find("X"))
7、index
# 返回子串在字符串中的索引,存在返回索引,不存在则报错
print(testStr.index("a"))
print(testStr.index("X"))
8、join
# 使用指定字符连接字符串
print("_".join(testStr))
# Z_h_a_n_S_a_n
9、lower、upper
# 转换字符串为小写 print(testStr.lower()) # zhansan # 转换字符串为大写 print(testStr.upper()) # ZHANSAN
10、strip、lstrip、rstrip
# 在字符串左边去掉指定的子串
print(testStr.lstrip("Z"))
# hanSan
# 在字符串右边去掉指定子串
print(testStr.rstrip("n"))
# ZhanSa
# 在字符串两边去掉指定子串
print(testStr.strip("x"))
11、partition
# 按照指定的子串分割字符串
print(testStr.partition("a"))
# ('Zh', 'a', 'nSan')
12、replace
# 替换字符串
print(testStr.replace("a","T",1))
# ZhTnSan
print(testStr.replace("a","T",2))
# ZhTnSTn
13、split
# 分割字符串
print(testStr.split("a"))
# ['Zh', 'nS', 'n']
14、swapcase
# 大小写互换 print(testStr.swapcase()) # zHANsAN
15、tiile
temp = "zhan ni hao" print(temp.title()) # Zhan Ni Hao
浙公网安备 33010602011771号