python的字符串(string)常用方法

# coding = utf-8
# capitalize方法将字符串的首字母大写
info = "happy dog"
new_info = info.capitalize()
print(new_info)  # Happy dog

# upper方法将字符串中的所有字符大写
# lower方法将字符串中的所有字符小写
info1 = "happy cat"
new_info1 = info1.upper()
print(new_info1)  # HAPPY CAT
new_info2 = info1.lower()
print(new_info2)  # happy cat

# swapcase方法将字符串中的大写改成小写,小写改大写
corner = "This is a Wall"
new_corner = corner.swapcase()
print(new_corner)  # tHIS IS A wALL

# zfill方法将字符串补齐(超出的补齐,不足的返回原值)
str_a = "love"
new_str_a = str_a.zfill(5)  # 0love
new_str_a = str_a.zfill(10)  # 000000love
new_str_a = str_a.zfill(2)  # love
print(new_str_a)

# count方法统计字符串中出现字符的次数
str_c = "monkey is an animal"
new_str_c = str_c.count("a")    # 3
print(new_str_c)
new_str_c = str_c.count("an")
print(new_str_c)  # 2

# startswith方法字符串以指定的值开头则返回 Ture or False
# endswith方法字符串以指定的值开头则返回 Ture or False
info_s = "hello world"
new_info_s = info_s.startswith("hello")
new_info_s1 = info_s.startswith("world")
print(new_info_s)   # Ture
print(new_info_s1)  # False
new_info_s = info_s.endswith("world")
new_info_s1 = info_s.endswith("hello")
print(new_info_s, new_info_s1)  # True False

# find,index方法返回函数中的索引值
info_f = "today the sunny is nice"
new_info_f = info_f.find("d")
new_info_f1 = info_f.find("e")
info_11 = info_f.index("e")
print(info_11)      # 8
print(new_info_f)   # 2
print(new_info_f1)  # 8

# replace方法替换字符串中的字符
str_r = " i love eat banana"
new_str_r = str_r.replace("love", "like")
print(new_str_r)  # i like eat banana

# strip去除字符串中的空格
str_q = "  qq today not online "
new_str_q = str_q.strip()
print(str_q)
print(new_str_q)

# 字符串的格式化 float
age = 17
top = 170
kg = 50
info_j = "小明今年{}岁,身高{}cm,体重:{}kg"
new_info_j = info_j.format(age, top, kg)
print(new_info_j)  # 小明今年17岁,身高170cm,体重:50kg

 

你可能感兴趣的:(python,python,字符串)