教为学:Python学习之路(四):字符串

教为学:Python学习之路(四):字符串

字符串也是序列

我之所以说这句话,也就是说序列的操作,字符串同样都具备。

格式化字符串

我对格式化字符串特别有感情,因为很久很久以前,我学第一门语言C语言的时候,在我学习谭浩强的那本书的时候,我花了多少时间去记忆那格式化字符的标号。现在全忘了,很多的时候,我们学了很多没一点用的东西,所以很多的时候,我们要记住重点。那些格式,你要用的时候,去查呗,记有病吗?而且那破东西十分打击别人的信心。

代码如下:

  1. print "int:%d,string:%s"%(33,"String")

结果如下:

  1. int:33,string:String

在要打印的字符串里面用%d和%s进行占位,然在整列字符串后面%()加入要代入的字符串。

至于%d是整数占位符,%s是字符串占位符。

当有一天这张表都救不了你了,搜索是最简单的方法?

方法

Python有最方便的帮助文档,所以一个个的方法演示没什么必要。

源码:

  1. a="str"
  2. print dir(a)

结果:

  1. ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

常用方法在下面,我们演示几个查找帮助。

  1. a="str"
  2. help(a.find)
  3.  
  4. Help on built-in function find:
  5.  
  6. find(...)
  7.     S.find(sub [,start [,end]]) -> int
  8.  
  9.     Return the lowest index in S where substring sub is found,
  10.     such that sub is contained within S[start:end]. Optional
  11.     arguments start and end are interpreted as in slice notation.
  12.  
  13.     Return -1 on failure.

第一个参数为你所要查找的字符串,从哪里开始查找和到哪里结束查找是可选的。

返回值是整形,当返回值为-1的是时候表示查找失败。

  1. a="strtrtr"
  2. help(a.replace)
  3.  
  4. Help on built-in function replace:
  5.  
  6. replace(...)
  7.     S.replace(old, new[, count]) -> string
  8.  
  9.     Return a copy of string S with all occurrences of substring
  10.     old replaced by new. If the optional argument count is
  11.     given, only the first count occurrences are replaced.

三个参数第一个是需要替代的字符串,第二个是被替代的字符串,第三个可选是旧的字符串里面的第几个匹配的被替换。

查看帮助就不一一介绍了。

posted @ 2013-06-05 21:42  教为学  阅读(740)  评论(0编辑  收藏  举报