• [Python Study Notes]字符串操作


                         

     字符串操作    

                                                                       

    a.字符串格式化输出

    1 name = "liu"
    2 print "i am %s " % name
    3    
    4 #输出: i am liu  
    6 PS: 字符串是 %s;整数 %d;浮点数%f

     b.查找字符串(find)

    1 str.find(str, start=0, end=len(mystr))   # 检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1
    1 >>> str = 'xinge 好帅'
    2  
    3 >>> str.find('xing')
    4 0
    5  
    6 >>> str.find('')
    7 6

     c.查找替换字符串中内容(replace)

    1 mystr.replace(str1, str2, mystr.count(str1))  # 把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.
    1 >>> str = 'abcabcabc'
    2  
    3 >>> str.replace('a','xinge',2)
    4 'xingebcxingebcabc'

     d.以str为分割符切片(split)

    mystr.split(str=" ", 2) # 以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串
    1 >>> str = 'a
    b	c'
    2  
    3 >>> str
    4 'a
    b	c'
    5  
    6 >>> str.split()
    7 ['a', 'b', 'c']

     f.将字符串首字母大写(capitalize)

    1 >>> str='abc'
    2  
    3 >>> str.capitalize()
    4 'Abc'

    g.把字符串的每个单词首字母大写(title)

    1 >>> str = "hello world"
    2  
    3 >>> str.title()
    4 'Hello World'

     h.startswith,endswith

    1 startswith  # 检查字符串是否是以str 开头, 是则返回 True,否则返回 False
    2 endswith  # 检查字符串是否以str结束,如果是返回True,否则返回 False.

     i.upper,lower

    1 upper  # 转换 mystr 中所有字符为大写
    2 lower  # 转换 mystr 中所有字符为小写

     j.strip,lstrip,rstrip

    1 strip  # 清除左右两边的空格
    2 lstrip  # 清除左边的空格
    3 rstrip  # 清除右边的空格

    k.join

    1 mystr.join(str)  # mystr 中每个字符后面插入str,构造出一个新的字符串

                                                                               欢迎补充!                                                                

    最有用的语言,除了English,其次可能是Python
  • 相关阅读:
    Git哲学与使用
    save
    http://www.onvif.org/onvif/ver20/util/operationIndex.html
    图标
    C#高性能大容量SOCKET并发(一):IOCP完成端口例子介绍(转)
    一种基于PTP 协议的局域网高精度时钟同步方法(转)
    WPF中的数据模板(DataTemplate)(转)
    WPF中的ControlTemplate(控件模板)(转)
    也来说说C#异步委托(转)
    C#委托的介绍(delegate、Action、Func、predicate)(转)
  • 原文地址:https://www.cnblogs.com/liu66blog/p/8157878.html
Copyright © 2020-2023  润新知