python切片,字符串的常见操作

python切片,字符串的逆序

#encoding=utf-8 
name = "abcdefghijklmn"
age = 20
print("%s的年龄为%d"%(name,age))            #abcdefghijklmn的年龄为20
print("我的年龄为%d"%age)            #我的年龄为20

print(name[2:-2])       #输出为cdefghijkl
print(name[2:])         #输出为cdefghijklmn
print(name[2:-2:2])     #输出为cegik(第一个2为起始位置,第二个-2为终止位置,第三个2为步长,不写默认步长为1)
print(name[-2:])        #输出为mn
print(name[::-1])       #输出为nmlkjihgfedcba,对一个字符串进行逆序

字符串的基本操作

Mystr = "Hello world itcast and itcastxxxcpp!"
print(Mystr.find("world"))      #输出为6,在原字符串中第一次出现位置的下标
print(Mystr.find("shihao"))     #输出为-1,无法找到输出-1
print(Mystr.rfind("itcast"))    #输出为23, rfind为从后向前查找
# print(Mystr.index("world1"))    #ValueError,无法查到时ValueError,其他与find相同
print(Mystr.count("itcast"))    #输出为2,查找itcast的个数

print(Mystr.replace("world","WORLd"))   #输出为Hello WORLd itcast and itcastxxxcpp!,  不会改变原来的字符串
print(Mystr.replace("itcast","ITCAST")) #输出为Hello world ITCAST and ITCASTxxxcpp!,   默认替换所有
print(Mystr.replace("itcast","ITCAST",1)) #输出为Hello world ITCAST and itcastxxxcpp!,   1为替换一次
print(Mystr.split(" ")) #输出为['Hello', 'world', 'itcast', 'and', 'itcastxxxcpp!'], 以空格切割,结果为一个列表
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值