字符串格式化

% 方法

1、字符宽度和精度 '%x.yf'

d/i/o/u/x/X/e/E/f/F/g/G/C/r(repr 转换任何对象)/s(str)

2、符号、对齐、填充

+标出数字正负号

-左对齐数值

""正数前加上空格

0用0填充空位

.format 方法

<居左, >为居右,^为居中

前面添加: 标记字符串格式化,:x>y 表示前面填充x、右对齐、字符串宽度为y

class Person:  
    def __init__(self, name, age):
        self.name, self.age = name, age

    def __str__(self):
        return 'This guy is {self.name},is {self.age} old'.format(self=self)

print('*' * 10 + " index  " + "*" * 10)  
print('{name} haha'.format(name='qinfei'))  
print('{},{}'.format('qinfei', 18))  
print('{1},{0},{1}'.format('qinfei', 23))  
print('*' * 10 + " class  " + "*" * 10)  
p = Person("qinfei", 23)  
print(p)  
# 通过下标映射
print('*' * 10 + "markdown" + "*" * 10)  
p = ['qinfei', 18]  
print('{0[0]},{0[1]}'.format(p))  
# 格式限定
print('*' * 10 + " format " + "*" * 10)  
print('{:>8}'.format('189'))  
print('{:0>8}'.format('189'))  
print('{:a>8}'.format('189'))  
# 精度与类型
print('{:.2f}'.format(321.33345))  
# 进制
print('{:b}'.format(17))  
ha = "haha"  
print(' '.join('{:02x}'.format(ord(c)) for c in ha))  

Template 方法

link http://www.thinksaas.cn/topics/0/590/590916.html

string.Template()

正则替换

字符串模板的安全替换(safe_substitute)

附字符串方法:

a = ['H', 'e', 'l', 'l', 'o']  
y = 'cccccc'  
b = y.join(a)  
print(b)

c = "  hello i am qinfei!  "  
d = c.split(' ')  
print(d)

x = c.replace(' ', '')  
print(x)

e = c.strip()  
print(e)  
e = list(d)  
print(e)  

类的继承

class Calculator:  
    def calculate(self, expression):
        self.value = eval(expression)


class Talker:  
    def talk(self):
        print("Hi, my value is ", self.value)


class TalkingCalculator(Calculator, Talker):  
    pass


tc = TalkingCalculator()  
tc.calculate('2*3')  
tc.talk()  

捕获异常对象

try:  
    x = int(input('Enter x:'))
    y = int(input('Enter y:'))
    print(x/y)
except (ZeroDivisionError, TypeError, NameError) as e:  
    print('Bugs:', e)