Python 3 日记 - 字符串(一)

来源:互联网 发布:静态头像源码 编辑:程序博客网 时间:2024/06/05 11:07

注:以下内容为学习笔记,多数是从书本、资料中得来,只为加深印象,及日后参考。然而本人表达能力较差,写的不好。因非翻译、非转载,只好选原创,但多数乃摘抄,实为惭愧。但若能帮助一二访客,幸甚!


好好学习,天天向上

积土成山,风雨兴焉;积水成渊,蛟龙生焉;积善成德,而神明自得,圣心备焉。故不积跬步,无以至千里;不积小流,无以成江海。骐骥一跃,不能十步;驽马十驾,功在不舍。锲而舍之,朽木不折;锲而不舍,金石可镂。

《Python Cookbook》 第一章 文本 学习日记


2012-12-03 星期一

用每次处理一个字符的方式处理字符串

1)创建一个列表,列表的子项是字符串的字符(每个子项是一个长度为1 的字符串)

the_string = 'hi'the_list = list(the_string)print('the result of the list: ')print(the_list)
结果:

the result of the list: 
['h', 'i']

2)用for 语句循环遍历字符串

def do_something_with(c):    print(c)for c in the_string:    do_something_with(c)
结果:

h
i
3)用列表推导中的for 来遍历

results1 = [do_something_with(c) for c in the_string]
结果:
h
i

4)用内建的map,python3 中该函数返回为迭代器

def do_something_else(c):    return c * 2results2 = map(do_something_else, the_string)print(type(results2))print(results2)for i in results2:    print(i)
结果:

<class 'map'>
<map object at 0x024EBE10>
hh
ii
返回值为‘map’类型

5)使用set获得字符串的所有字符的集合

# 使用set获得字符串的所有字符的集合# Python3 中set已经属于标准库,# 而Python2中 需要用sets.Set,使用前要import sets.Setmagic_chars = set('abracadabracdef')poppine_chars = set('foaeiwjfiodasjgfdksyutreowdskfjaowier')# 下面语句打印的结果是个集合print(magic_chars & poppine_chars)# 下面语句打印结果是字符串print(''.join(magic_chars & poppine_chars))
结果:

{'a', 'r', 'e', 'd', 'f'}
aredf


2012-12-04 星期二

字符和字符值之间的转换

1)ord,chr

# 将一个字符转化为相应的ASCII(ISO)或者Unicode码print(ord('a'))# python 2 中写作u'\u2020'表示这是一个Unicode 字符串,# 但Python 3中字符串总是Unicode形式的,所以不需要前面的uprint(ord('\u2020'))# 将ASCII(ISO)或Unicode码转换为字符print(chr(97))# 在python3.0只用chr()就可以了。在python2.6用chr()和unichr()# print(chr(8224))# 在Myeclipse中上句会有UnicodeEncodeError: 'gbk' codec can't # encode character '\u2020' in position 0 错误# 直接在Python Shell中则不会出错,不知为何

结果:

97
8224
a

2)repr,str

# python 3 中只有一种字符串类型即Unicode字符串,所以str() 函数# 可完成所有将对象强制转化成字符串的任务print(str((8224)))# chr() 将一个整数转换成Unicode# repr()是将一个对象转成字符串显示print(repr(chr(97)))print(repr(str(97)))
结果:

8224
'a'
'97'

3)map

for n in map(ord, 'ciao'):    print(n)    print('*****************************************************')s = ''for c in map(chr, range(97, 100)):    s += ''.join(c)print(s)
结果:

99
105
97
111
*****************************************************
abc

2012-12-05 星期三

测试一个对象是否是类字符串

准确的说,测试这个对象是否具有类似于字符串的行为模式

1)isinstance

# python 2 中内建类型basestring 是str和unicode类型的共同基类,# 任何类字符串的用户自定义类型都应该从基类basestring派生#def isAString(anobj):#    return isinstance(anobj, basestring)# python 3 中只有一种字符串即unicode,所以只有strdef isAString(anobj):    return isinstance(anobj, str
2)Python特色的方法

获得事后原谅总是比事先得到许可要容易的多(It's easier to ask forgiveness than permission, EAFP)

# 上面的方法对于python 标准库中的UserString 模块提供的UserString# 类的实例,完全无能为力def isStringLike(anobj):    try: anobj + ''    except: return False    else: return True

2012-12-06 周四

字符串对齐、去除空格、合并

1)字符串对齐

# 左对齐,居中对齐,右对齐print('|', 'gzdk'.ljust(20), '|', 'gzdk'.center(20), '|', 'gzdk'.rjust(20))# 指定填充字符print('gzdk'.center(20, '*'))
输出:

| gzdk                 |         gzdk         |                 gzdk
********gzdk********
2)去除字符串两端的空格(或其他符号)

# 去除字符串两端的空格print('**********************************************')org_str = '       python       'print('|', org_str.lstrip(), '|', org_str.rstrip(), '|', org_str.strip(), '|')# 去除字符串两端的指定字符org_str = '***+++*+*+    python    ++*+*+*+*+++'print('|', org_str.strip('+*'), '|')print('|', org_str.strip('+* '), '|')
输出:
**********************************************
| python        |        python | python |
|     python     |
| python |
3)合并字符串

# 合并字符串,字符串拼接print('**********************************************')str1 = 'abc'str2 = 'python'str3 = 'c++'str_pieces = [str1, str2, str3]large_str = ''.join(str1)print(large_str)# str.join Found at: builtins S.join(iterable) -> str # Return a string which is the concatenation of the strings # in the iterable. The separator between elements is S.# 下面的语句输出:apythonbpythonclarge_str = str2.join(str1)print(large_str)# 下面语句输出:abcpythonc++large_str = ''.join(str_pieces)print(large_str)# 使用字符串格式化操作符% 拼接字符串large_str = 'language %s %s is good' % (str2, str3)print(large_str)# 使用 + 操作符拼接字符串large_str = 'language ' + str2 + ' ' + str3 + ' is good'print(large_str)large_str = ''for s_piece in str_pieces:    large_str += s_pieceprint(large_str)
输出:

**********************************************
abc
apythonbpythonc
abcpythonc++
language python c++ is good
language python c++ is good
abcpythonc++


2012-12-07 周五

按字符、单词反转字符串及字符串的包含

1.将字符串逐字符或逐词反转

org_str = 'Hello world and hello    Python'print(org_str)# 使用“步长”为-1的特别的切片方法逐字符反转rev_chars = org_str[::-1]print(rev_chars)# 按单词反转,先创建一个单词列表,将这个列表反转# 最后用join将其合并,并在相邻两词之间插入一个空格rev_words = org_str.split()rev_words.reverse()rev_words = ' '.join(rev_words)print(rev_words)# 简练紧凑的代码rev_words = ' '.join(org_str.split()[::-1])print(rev_words)# 使用正则表达式分隔原字符串,这样可以反转单词同时不改变原先的空格(如Tab)import rerev_words = re.split(r'(\s+)', org_str)rev_words.reverse()rev_words = ''.join(rev_words)print(rev_words)# 过于紧凑的代码,失去了可读性,不是好的Python代码rev_words = ''.join(re.split(r'(\s+)', org_str)[::-1])print(rev_words)# 内建函数reversed 反转单词rev_words = ' '.join(reversed(org_str.split()))print(rev_words)rev_words = ''.join(reversed(re.split(r'(\s+)', org_str)))print(rev_words)# 内建函数reversed 反转字符rev_chars = ''.join(reversed(org_str))print(rev_chars)
输出:

Hello world and hello    Python
nohtyP    olleh dna dlrow olleH
Python hello and world Hello
Python hello and world Hello
Python    hello and world Hello
Python    hello and world Hello
Python hello and world Hello
Python    hello and world Hello
nohtyP    olleh dna dlrow olleH

2.检查字符串中是否包含某字符集合中的字符

# 检查字符串中是否包含某字符集合中的字符print('****************************************************')L1 = [1, 2, 3, 3]L2 = [1, 2, 3, 4]# 检查序列seq是否包含有aset中的项def containsAny(seq, aset):    for c in seq:        if c in aset: return True    return Falseprint(containsAny(L1, L2))# 基于集合的方法def containsAny2(seq, aset):    return bool(set(aset).intersection(seq))print(containsAny2(L1, L2))# 检查序列seq中的项是否都在aset中def containsOnly(seq, aset):    for c in seq:        if c not in aset: return False    return Trueprint(containsOnly(L1, L2))# 与上面类似,a.defference(b) 返回在a中,不在b中的元素# 故下面的语句表示不存在如下情况:有元素在aset中,但不在seq中的元素# 即检查aset中的所有元素,都在seq中出现def containsAll(seq, aset):    return not set(aset).difference(seq)print(containsOnly(L1, L2))print(containsOnly(L2, L1))print(containsAll(L1, L2))print(containsAll(L2, L1))
输出:
****************************************************
True
True
True
True
False
False
True

2012-12-08

bytes 的maketrans 和translate方法及闭包

# bytes.translate(table[, delete]) # bytearray.translate(table[, delete]) # Return a copy of the bytes or bytearray object where all bytes # occurring in the optional argument delete are removed, and the # remaining bytes have been mapped through the given translation table, # which must be a bytes object of length 256.# You can use the bytes.maketrans() method to create a translation table.# 大意是若给出了delete参数,则将原来的bytes中的属于delete的字符删除,剩下的字符要按照# table中给出的映射来进行映射# Set the table argument to None for translations that only delete characters:# 若table参数为None,则只删除不映射,故下面语句输出:# b'rd ths bk'print(b'read this book'.translate(None, b'aeiou'))# static bytes.maketrans(from, to) # static bytearray.maketrans(from, to) # This static method returns a translation table usable for bytes.translate() # that will map each character in from into the character at the same # position in to; from and to must be bytes objects and have the same length.# 大意是返回一个转换表共bytes.translate使用# 下面的table把abcd映射为ABCD,则输出为:# b'rD ths Bk'table = bytes.maketrans(b'abcd', b'ABCD')print(b'read this book'.translate(table, b'aeiou'))# 对字符串的translate方法的简单封装,以更容易使用# 下面方法为生成一个从frm到to 的映射# delete是需要删除的字符# keep 是要保留的字符# 下面的实现优先考虑delete,即delete和keep有重叠时,delete优先def my_translator(frm = b'', to = b'', delete = b'', keep = None):    # 若长度为1,则所有frm映射到同一个to    if len(to) == 1:        to = to * len(frm)            # 使用frm 到to 构建一个映射表    trans = bytes.maketrans(frm, to)        if keep is not None:        # 获取空映射表的所有字符        allchars = bytes.maketrans(b'', b'')        # 1)从keep中去除delete中包含的字符,即keep与delete有重合时,优先考虑delete        # 2)delete为从全体字符中除去keep,即不在keep的都删掉        keep = keep.translate(allchars, delete)        delete = allchars.translate(allchars, keep)            # 闭包(closure)是一个内层函数,由一个名字(变量)来指代,而这个名字(变量)对于外层包含它的函数    # 而言,是本地变量。    def my_translate(s):        return s.translate(trans, delete)        return my_translate# 关于闭包的简单用法def make_adder(addend):    def adder(augend):        return augend + addend    return adder# 执行第一句,将产生内层函数adder的一个闭包,这个闭包在内部引用了名字addend# 而addend绑定到数值1; 执行第二句,将产生另一个闭包,这次addend绑定到2# 故下面输出为101和102adder1 = make_adder(1)adder2 = make_adder(2)print (adder1(100), adder2(100))# 使用上面定义的my_translator# 只保留数字digits_only = my_translator(keep = b'0123456789')print(digits_only(b'hello python 123-456'))# 删除所有数字no_digits = my_translator(delete = b'0123456789')print(no_digits(b'hello python 123-456'))# 用*替换数字digits_to_hash = my_translator(frm = b'0123456789', to = b'*')print(digits_to_hash(b'hello python 123-456'))# delete与keep有重合时的情况trans = my_translator(delete = b'aeiou', keep = b'opqxy')print(trans(b'hello python 123-456'))
输出:

b'rd ths bk'
b'rD ths Bk'
101 102
b'123456'
b'hello python -'
b'hello python ***-***'
b'py'

7.过滤字符串中不属于指定集合的字符

# 生成所有字符的可复用的字符串all_chars = bytes.maketrans(b'', b'')# 返回一个函数,此函数接受一个字符串为参数,并返回字符串的一个部分拷贝# 此拷贝只包含在keep中的字符,keep必须是一个普通字符串def make_filter(keep):    # 生成一个由所有不在keep中的字符组成的字符串:keep的补集,即我们要删除的字符    del_chars = all_chars.translate(all_chars, keep)        # 生成并返回需要的函数(作为闭包)    def the_filter(s):        return s.translate(all_chars, del_chars)        return the_filterjust_vowels = make_filter(b'aeiouy')print(just_vowels(b'hello python, hello 123'))# 使用set,此方法也适用于Unicodeclass Keeper(object):    def __init__(self, keep):        self.keep = set(map(ord, keep))    def __getitem__(self, n):        if n not in self.keep:            return None        return chr(n)    def __call__(self, s):        return s.translate(self)    make_filter = Keeperjust_vowels = make_filter('aeiouy')print(just_vowels('hello python, hello 1234'))
输出:
b'eoyoeo'
eoyoeo