python基础知识(7)-字符串

基础知识(7)

数据容器–字符串

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

    例如:“nihao”

  • 字符串和元组一样是无法修改

字符串的内容可以通过下标索引取得

  • 从前向后,下标从0开始

  • 从后向前,下标从-1开始

my_str = "nihao and mthgh"
# 通过下标索引取值
value = my_str[2]
value2 = my_str[-15]
print(f"从字符串{my_str}取下标为2的元素,值是:{value},取下标为-16的元素的值是:{value2}")

#从字符串nihao and mthgh取下标为2的元素,值是:h,取下标为-16的元素的值是:n
字符串常见操作:
  1. 查找特定字符串

  2. 字符串的替换

  3. 字符串的分割

  4. 字符串的规整操作

    去前后的空格

    去前后指定字符串

  5. 统计字符串中某字符串的出现次数

  6. 统计字符串的长度

  7. 字符串的遍历

1.查找特定字符串(index方法)
my_str = "nihao and mthgh"
value = my_str.index("and")
print(f"在字符串{my_str}中查找and,其下标是:{value}")

#在字符串nihao and mthgh中查找and,其下标是:6
2.字符串的替换(replace方法)
my_str = "nihao and mthgh"
new_my_str = my_str.replace("it","黑马")
print(f"替换后为:{new_my_str}")

#替换后为:nihao and mthgh
3.字符串的分割(strip方法)
my_str = "hello python nihao mthgh"
my_str_list = my_str.split(" ")
print(f"将字符串{my_str}进行splic切分后得到:{my_str_list},类型是:{type(my_str_list)}")

#将字符串hello python nihao mthgh进行splic切分后得到:['hello', 'python', 'nihao', 'mthgh'],类型是:<class 'list'>
4.字符串的规整操作
my_str = "hello python nihao mthgh"
my_str = "   nihao and mthgh  "
new_my_str = my_str.strip()    #不传入参数,去除首尾空格
print(f"字符串{my_str}被strip后,结果是;{new_my_str}")

#字符串   nihao and mthgh  被strip后,结果是;nihao and mthgh

其他情况:

my_str = "12nihao and imthgh21"
new_my_str = my_str.strip("12")
print(f"字符串{my_str}被strip('12')后,结果是:{new_my_str}")

#字符串12nihao and imthgh21被strip('12')后,结果是:nihao and imthgh
5.统计字符串中某字符串的出现次数
my_str = "nihao and mthgh"
count = my_str.count("mt")
print(f"字符串{my_str}中it出现的次数是:{count}")

#字符串nihao and mthgh中it出现的次数是:1
6.统计字符串的长度
my_str = "nihao and mthgh"
num = len(my_str)
print(f"字符串{my_str}的长度是:{num}")

#字符串nihao and mthgh的长度是:15
7.字符串的遍历
my_str = "明天会更好"
index = 0
while index <len(my_str):
    print(my_str[index])
    index += 1

#明
#天
#会
#更
#好
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YA10JUN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值