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!'], 以空格切割,结果为一个列表