@kangwg
2017-06-18T15:46:32.000000Z
字数 2523
阅读 855
layout: post
title: "python String"
subtitle: "python字符串"
date: 2017-04-09 12:00:00
author: "kangwg"
catalog: true
categories: "python"
'%10f' % pi3.141593'%10.2f' % pi3.14'%.2f%' % pi3.14'%.5s' % 'Guido van Rossum'Guido'%.*s' % (5,'Guido van Rossum')Guidophonebook={'Cecil':'110'}'Cecil's phone number is %(Cecl)s.' % phonebookCecil's phone number is 110.
copy 修改不会变,增加删除会变 避免这个可以采用deepcopy
x={'x':'1','y':'2','z':['1','2','3']}y = x.copy()y['x']='xx'y['z'].remove('1')y['z'].append('4'){'y': '2', 'x': 'xx', 'z': ['2', '3', '4']}{'y': '2', 'x': '1', 'z': ['2', '3', '4']}
假:False None () "" 0 [] {}
其它的都是真
调试使用
age = -1assert 0<age<100,'The age must be realistic'AssertionError: The age must be realistic
zip 将序列压缩一对一组合,返回元组列表,当两系列的长度不同时,最短序列用完停止
names = ['anne','beth','george','domon']ages = [12,45,32,102]for name,age in zip(names,ages):print name,'is',age,'years old'
enumerate 提供迭代索引和值
for index,string in enumerate(names):if 'ann' in string:names[index] = '[censored]'
在循环中增加else,它仅在没有调用break时执行
from math import sqrtfor n in range(99,81,-1):root = sqrt(n)if root==int(root):breakelse:print "Didn't find it"
[x*x for x in range(10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81][x*x for x in range(10) if x % 3==0][0, 9, 36, 81][[x,y] for x in range(3) for y in range(3)][[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
exec "print 'hello'" in scope
in scope 表示为单独的命名空间,不会有变量和实际中的变量冲突
4. eval 计算字符串的数字表达式的值
eva('2*3')
def print_param(greeting,name):print greeting,nameprint_param(name="hello",greeting="word")word hellodef print_param(name="hello",greeting="word"):print greeting,nameprint_param(greeting='good')good hello
def print_param(title,*params):print paramsprint_param('test',1,2,3)( 1, 2, 3)
def print_params(x,y,z=3,*pospar,**keypar):print x,y,zprint posparprint keyparprint_params(1,2,4,5,6,p=1,k=2)1 2 4(5, 6){'p': 1, 'k': 2}
def add(x,y):print x+yparams=(1,2)add(*params)
def print_params(**x):print x.get('name'),x.get('age')params = {'name':'smith','age':'18'}print_params(**params)
class Class:def method(self):print 'I have a self'def function():print 'I dont....'instance = Class()instance.method()instance.method = functioninstance.method()I have a selfI dont....
class Bird:song = 'Squaawk'def sing(self):print self.songbird = Bird()bird.sing()birdsong = bird.singbirdsong()SquaawkSquaawk