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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值