Python基础笔记系列八:字符串的运算和相关函数

  本系列教程供个人学习笔记使用,如果您要浏览可能需要其它编程语言基础(如C语言),why?因为我写得烂啊,只有我自己看得懂!!

  • 字符串的运算
    1.字符串的加法和乘法
      
    python中不但支持字符串相加,还支持字符串的乘法,使用起来相当方便。加法就是将两个字符串连接在一起,而乘法就是字符串的多次相加。
    例子:
    1 str8 = 'hello '
    2 str9 = 'world!'
    3 #字符串连接
    4 print str8+str9 
    5 #实现10个段横线的输出
    6 print "-"*10
    7 #输出3个hello
    8 print str8*3 

    输出:

    1 hello world!
    2 ----------
    3 hello hello hello 

    2.字符串的成员运算符
      
    1)in和not in 运算:in 运算用于判断某个字符或子串是否在字符串中,not  in运算符与in 运算相反用于判断某个字符或子串是否不在字符串中。
    例子:

    1 #如果字符串中包含给定的字符串,返回True
    2 str8 = 'hello '
    3 print 'he' in str8
    4 #如果字符串中不包含给定的字符串,返回True
    5 print 'hc' not in str8

    输出:

    1 True
    2 True

      2)字符串的格式化(支持占位符)
    例子:

    1 #字符串的格式化(支持占位符)
    2 dic = ('yyc',50)
    3 print 'my name is %s,weight is %d kg.'%dic

    输出:

    my name is yyc,weight is 50 kg.
  • 字符串函数
    字符串拥有很多函数,下面的例子中是最常用的,以例子来说明。
    例子:

     1 mystr = 'hello world start leaning and hello and world!'
     2 print mystr.find('and') #查找字符串中第一个'and'出现的位置
     3 print mystr.find('and',27) #从第27的位置开始找
     4 print mystr.find('and',0,len(mystr)) #从第一个字符到字符串结尾找第一个'and'出现的位置,可以缺省start ,end即起止参数
     5 #-----mystr.rfind() 从右开始查找
     6 print mystr.index('and')  #和find差不多,但是index中的参数在mystr中不存在则会抛出异常
     7 print mystr.count("and") #统计'and'出现的次数,同样和find一样可以有3个参数
     8 mystr1 = mystr.encode(encoding="utf-8")   #按指定编码方式编码
     9 print type(mystr1)    
    10 mystr2 = mystr1.decode(encoding="utf-8",errors="strict")  #按指定编码方式解码,
    11 #errors参数为strict,如果编码错误会抛出ValueError异常,除非errors指定的是ignore或replace
    12 print mystr2
    13 print type(mystr2)
    14 print mystr.replace('and','or') #字符串替换函数,返回替换后的字符串,但是mystr本身并没有改变,除非mystr=mystr.replace('and','or')
    15 print mystr
    16 print mystr.replace('and','or',1) #只替换一次
    17 print mystr.split(' ') #按照空格进行分割,放到一个列表里
    18 print mystr.split(' ',3)#按照空格分割成4个子串
    19 #****************另外字符串还有很多判断函数(查文档吧,太多了)**********************

    输出:

     1 26
     2 36
     3 26
     4 26
     5 2
     6 <type 'str'>
     7 hello world start leaning and hello and world!
     8 <type 'unicode'>
     9 hello world start leaning or hello or world!
    10 hello world start leaning and hello and world!
    11 hello world start leaning or hello and world!
    12 ['hello', 'world', 'start', 'leaning', 'and', 'hello', 'and', 'world!']
    13 ['hello', 'world', 'start', 'leaning and hello and world!']


      

    扫描二维码关注公众号,回复: 60734 查看本文章

猜你喜欢

转载自www.cnblogs.com/hyyq/p/8922117.html