---
title: "python cookbook（1）"
author: "flowercat"
date: "2009-04-16T17:23:40Z"
tags: []
slug: "python-cookbook-1"
draft: false
lastmod: "2009-04-17T16:10:17Z"
id: 368875
url: "https://flowercat.iteye.com/blog/368875"
---

#coding=utf8

#1.4   对准：字符串长度为参数定义的，字符的位置由函数决定
print '|', 'hej'.ljust(20), '|', 'hej'.rjust(20), '|', 'hej'.center(20), '|'


#1.5 删除首尾的字符，默认不带参数是删除首尾的空格。参数为字符串时，表明要删除的首尾的字符（只要这个字符在参数这个字符串里）
x = '    hej   '
print '|', x.lstrip(), '|', x.rstrip(), '|', x.strip(''), '|'
x = 'xyxxyy hejyx  yyx'
print '|'+x.lstrip('jyx')+'|'


#1.6将小字串合成大字串，join() 字串格式化操作符 %    
#因为在python中字符串是不可变的，使用+操作符连接小字串每次操作都会产生一个新的string，所以避免使用+连接大量的字串
pieces=
largestring=''.join(pieces) 
print largestring
largestring='%s %s something %s yet more' % (pieces,pieces,pieces)
print largestring 

#1.7 如何颠倒一个字符串中的字符或者单词， 
astring='abcdef'
print astring,''.join(reversed(astring)),reversed(astring)
#astring 扩展切片操作，-1是步长 ，对字符的情况建议使用扩展切片操作，因为reversed 这个内部函数,返回的是迭代器，而不是一个字符串

astring="Hello world!"
revwords = astring.split()     # string -> list of words
revwords.reverse( )             # reverse the list in place
revwords = ' '.join(revwords)  # list of strings -> string
print revwords
revwords = ' '.join(astring.split( ))
print revwords

#1.8 判断一个list中的元素是否在一个集合中
def containsAny(seq, aset):
    for c in seq:
        if c in aset: return True
    return False

import itertools
def containsAny(seq, aset):
    for item in itertools.ifilter(aset.__contains__, seq):
        return True
    return False
#ifilter( predicate, iterable) 
#Make an iterator that filters elements from iterable returning only those for which the predicate is True.
#If predicate is None, return the items that are true.
print bool(set().intersection(set()))