zoukankan      html  css  js  c++  java
  • Python 之字符串常用操作

    字符串表示:str与repr的区别
    str()函数把值转换为合理形式的字符串,便于理解
    repr()函数是创建一个字符串,以合法的Python表达式形式来表示值。
    如下:

    #-*-encoding:utf-8-*-
    print repr("hello repr")
    print str("hello str")
    
    运行结果:
    'hello repr'
    hello str
    
    
    字符串格式化:
    
    
    				字符串格式化转换类型
    转换类型					含义
    d ,i			带符号的十进制整数
    o				不带符号的八进制
    u 				不带符号的十进制
    x 				不带符号的十六进制(小写)
    X 				不带符号的十六进制(大写)
    e 				科学计数法表示的浮点数(小写)
    E 				科学计数法表示的浮点数(大写)
    f ,F 			十进制浮点数
    C 				单字符(接受整数或单字符字符串)
    r 				字符串(使用repr转换任意python对象)
    s 				字符串(使用str转换任意python对象)
    
    例如:
    commodity="name : %s ,price:%s" %("苹果","12.86")
    print commodity
    运行结果:
    name : 苹果 ,price:12.86
    [Finished in 0.2s]
    
    
    字符串常用方法:
    1.1 find()
    1.2 join()
    1.3 lower()
    1.4 replace()
    1.5 split()
    1.6 strip()
    
    
    
    find()方法,用于在一个比较长的字符串中查找子串,它返回第一个子串所在的索引,如果没有找到则返回-1。
    str_a="Hello, welcome to the Python world!"
    print str_a.find("o")    #打印第一次出现o字符的索引位置
    运行结果:
    4
    [Finished in 0.2s]
    
    
    join()方法,用于连接序列中的元素。(与split方法功能相反)
    url=["d:","program Files","python"]
    print "\".join(url)   #使用符号将列表连接成一个字符串
    运行结果:
    d:program Filespython
    [Finished in 0.2s]
    
    
    lower()方法,用于将字符串转化为小写字母
    str_a="ABCdef"
    print str_a.lower()    #将全部字符转化为小写字符
    运行结果:
    abcdef
    [Finished in 0.3s]
    
    
    replace()方法,用于将字符串中所有匹配项都替换成新的字符串。
    str_a="Hello, welcome to the Python world!"
    print str_a.replace("to","AAA")   #将字符串中的o字符,全部替换为AAA,并把替换后结果返回
    print str_a
    运行结果:
    Hello, welcome AAA the Python world! AAA
    Hello, welcome to the Python world! to
    [Finished in 0.2s]
    
    
    split()方法,用于将字符串根据特定字符进行分隔成列表。
    URL="d:\program Files\python"
    new_list=URL.split("\")   #根据出现\的位置,进行分隔
    print new_list
    运行结果:
    ['d:', 'program Files', 'python']
    [Finished in 0.2s]
    
    
    strip()方法,用于去除字符串两侧(不包含内容)空格的字符串。
    str_a="     hello ,everyone!    "
    print str_a
    print str_a.strip(" ")    #去除左右两边的空格
    运行结果:
         hello ,everyone!    
    hello ,everyone!
    [Finished in 0.3s]
    

      

  • 相关阅读:
    We7 2.7版:全拖拽建站 开源CMS
    We7 CMS 2.6RC2版本发布 开源CMS
    LINQ简易教程
    C# 引用 C# DLL
    ASP.NET中母版页与JavaScript控制的一点小问题
    LINQ连接远端数据库问题
    ASP.NET中自动生成XML文件并通过XSLT显示在网页中的方法
    【转载】常见逻辑错误
    因为压力大变得很郁闷的时候怎么办
    代码覆盖度C#代码监控工具NCover、Rational PureCoverage、BullseyeCoverage
  • 原文地址:https://www.cnblogs.com/JcHome/p/10090231.html
Copyright © 2011-2022 走看看