Python 字符串

字符串是 Python 中最常用的数据类型。我们可以使用引号 ( ’ 或 " ) 来创建字符串。

# 字符串
# 通过下标索引取值
mystr = "abcdefgh"
value = mystr[2]
print(f"获取下标为2的元素{value}")
# index()方法
values = mystr.index("c")
print(f"字符串中c的下标为{values}")
# replace()方法
newstr = mystr.replace("c", "a")
print(f"替换后的字符串{newstr}")
# split()方法
my_str = "a,b,c,d,e,f,g,h"
spstr = my_str.split(",")
print(f"切割后{spstr}")
# strip()方法 不传参数去除前后空格
my_strs = " abcdefgh "
newmy_strs = my_strs.strip()
print(F"字符串strip后是:{newmy_strs}")

my_strs1 = "32abcdefgh23"
newmy_strs1 = my_strs1.strip("23")
print(F"字符串strip传参后是:{newmy_strs1}")

# 统计字符串中某个字符穿线的次数
my_strs2 = "abcdefgha"
count = my_strs2.count("a")
print(f"字符串a出现次数{count}")
# 统计字符串的长度
num = len(my_strs2)
print(f"字符串长度是:{num}")

运行结果:
获取下标为2的元素c
字符串中c的下标为2
替换后的字符串abadefgh
切割后[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’]
字符串strip后是:abcdefgh
字符串strip传参后是:abcdefgh
字符串a出现次数2
字符串长度是:9

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值