Python-数据容器之str字符串

Python-数据容器之str字符串

一、简介

    字符串是字符的容器,一个字符串可以存放任意数量的字符。

与列表(list)、元组(tuple)相同的是字符串也可以通过下标的方式获取字符。从前往后,下标从0开始,从后往前,下标从-1开始。

注意:同元组一样,字符串是无法修改的容器。

二、常用操作

2.1、index()

    查找特定字符对应的下标索引值。语法:字符串.index(字符);

#1、index();str_01="hello word ! hello python!!";index_01=str_01.index("l");##元素l所在的下标是:2print(f"元素l所在的下标是:{index_01}");

2.2、replace()

    字符串替换。语法:字符串.replace(字符串1,字符串2);

功能:将字符串内的全部字符串1替换为字符串2,变成一个新的字符串。

str_01="hello word ! hello python!!";str_01_new=str_01.replace("p","P");print(f"替换前字符串:{str_01}");print(f"替换后字符串:{str_01_new}");#替换前字符串:hello word ! hello python!!#替换后字符串:hello word ! hello Python!!

2.3、split()

    字符串分割   语法:字符串.split(分割字符串);

功能:按照指定的分隔符将某个字符串拆分成多个字符串,并存入列表中。字符串本身并没有发生变化,而是得到一个全新的列表对象。

#split()str_01="hello word ! hello python! good";list_01=str_01.split("!");#拆分后的列表:['hello word ', ' hello python', ' good']print(f"拆分后的列表:{list_01}")

2.4、strip()

    字符串规整操作,常用于去除空格。

用法

    1、去除前后空格:字符串.strip(); 

    2、去除指定字符串(头或尾):字符串.strip("123")。

#strip()str_01="213hello word ! hello python! good 123";str_01_01=str_01.strip();#字符串str_01:213hello word ! hello python! good 123 规整后为:213hello word ! hello python! good 123print(f"字符串str_01:{str_01}规整后为:{str_01_01}")str_01_02=str_01.strip("123"); #只要头尾包含有指定字符序列中的字符就删除#字符串str_01:213hello word ! hello python! good 123规整后为:hello word ! hello python! good print(f"字符串str_01:{str_01}规整后为:{str_01_02}")

注意:123其实是传入“1”,“2”,“3”单个字符。

2.5、count()

    统计某个字符在字符串中出现的次数。字符串.count(字符串);

str_01="213hello word ! hello python! good 123";count_01=str_01.count("hello");#字符串hello出现的次数:2print(f"字符串hello出现的次数:{count_01}")

2.6、len()

    统计字符串内字符的个数。len(字符串);

str_01="213hello word ! hello python! good 123"num_01= len(str_01)#字符串str_01的长度:38print(f"字符串str_01的长度:{num_01}")

2.7、for\while循环遍历

    和列表、元组一样,不再讲述。

三、总结

    1、只可以存储字符串,支持下标索引,且运行重复;

    2、长度任意(也受限于内存大小);

    3、不可以修改(增删等);

    4、支持for\while循环。

字符串大小比较:依据ASCII码表,一位一位的比较。

更多优秀文章,请扫码关注个人微信公众号或搜索“程序猿小杨”添加。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值