首页 > 代码库 > python学习笔记
python学习笔记
一。文本
1.每次处理一个字符
1)list
2)import sets
>>> import sets
>>> magic_chars=sets.Set(‘adboieihoejoewjo‘)
>>> enchar=sets.Set(‘eijowj‘)
>>> ‘‘.join(magic_chars & enchar) #集合的交集
‘ijeow‘
>>>
2.字符和字符值之间的转换
>>> print ord(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘a‘ is not defined
>>> print ord(‘a‘)
97
>>> print chr(‘99‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> print chr(99)
c
>>> print repr(str(99)
...
... )
‘99‘
3.测试一个对象是否是类字符串
>>> print isinstance(abc,basestring)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘abc‘ is not defined
>>> print isinstance(‘abc‘,basestring)
True
4.字符串对齐
>>> ‘abc‘.center(20,‘__‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: center() argument 2 must be char, not str
>>>
>>> print ‘abc‘.center(20,‘__‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: center() argument 2 must be char, not str
>>> ‘abc‘.center(20,‘_‘)
‘________abc_________‘
>>>
>>> ‘aaa‘.ljust(20,‘@‘)
‘aaa@@@@@@@@@@@@@@@@@‘
>>> ‘bbb‘.rjust(20,‘@‘)
‘@@@@@@@@@@@@@@@@@bbb‘
>>>
5.去除字符串两端的空格
>>> x=‘ p ‘
>>> x.ltrip()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ‘str‘ object has no attribute ‘ltrip‘
>>> x.lstrip()
‘p ‘
>>> x.rstrip()
‘ p‘
>>> x,strip()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘strip‘ is not defined
>>> x.strip()
‘p‘
>>>
6.合并字符串
7.将字符串逐次反转
#正则匹配 匹配空格
astring=‘Hello World‘
import re
#split(r‘()‘,string)
rewords=re.split(r‘(\s+)‘,astring)
‘ ‘.join(rewords)
8.检查字符串中是否包含某字符集合中的字符
9.简化字符串的translate的方法的使用
10.过滤字符串中不属于指定集合的字符
11.python 的itertools
本文出自 “王尼美的成人之路” 博客,转载请与作者联系!
python学习笔记