Goodspeed

导航

Python文本常量和模板——string

#!/usr/bin/python
#coding=utf-8
#http://docs.python.org/library/string.html
import string

#全部字母 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print string.ascii_letters 
print string.letters #根据地域来的
#全部小写字母 abcdefghijklmnopqrstuvwxyz
print string.ascii_lowercase
print string.lowercase
#全部大写字母 ABCDEFGHIJKLMNOPQRSTUVWXYZ
print string.ascii_uppercase
print string.uppercase
#全部数字
print string.digits
#16进制? 0123456789abcdefABCDEF
print string.hexdigits
#所有的空格 \t\n\x0b\x0c\r 
print string.whitespace
#可打印字符(包括digits, letters, punctuation, and whitespace)
print string.printable
#标点符号
print string.punctuation
#不知道干嘛的01234567
print string.octdigits

#字符串格式化
"{0} {1}".format("hello", "world")
"{1} {0}".format("world", "hello")
"{} {}".format("hello") #2.7 Only
"{a} {b}".format(a= "hello",b ="world")

#百分比,保留二位小数
'Correct answers: {0:.2}'.format(1.00/3)
'Correct answers: {0:.2%}'.format(1.00/3)
import datetime
d = datetime.datetime.now()
'{0:%Y-%m-%d %H:%M:%S}'.format(d)

#模板
from string import Template
s = Template('$a $b')
s.substitute(a='hello', b='world')

"hello".find("l") #2
"hello".rfind("l") #3

"hello".index("l") #2 如果没找到会抛ValueError异常

"hello".count("l") #2

posted on 2012-08-03 18:02  Goodspeed  阅读(1275)  评论(0编辑  收藏  举报