Python中的string模块的学习

来源:互联网 发布:2016最流行的编程语言 编辑:程序博客网 时间:2024/06/02 18:03
>>> import string
>>> string.ascii_letters'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'>>> string.ascii_lowercase'abcdefghijklmnopqrstuvwxyz'>>> string.ascii_uppercase'ABCDEFGHIJKLMNOPQRSTUVWXYZ'>>> string.digits'0123456789'>>> string.hexdigits'0123456789abcdefABCDEF'>>> string.letters'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'>>> string.lowercase'abcdefghijklmnopqrstuvwxyz'>>> string.uppercase'ABCDEFGHIJKLMNOPQRSTUVWXYZ'>>> string.octdigits'01234567'>>> string.punctuation'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'>>> string.printable'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'>>> string.whitespace'\t\n\x0b\x0c\r>>> '{0}, {1}, {2}'.format('a', 'b', 'c')'a, b, c'>>> '{}, {}, {}'.format('a', 'b', 'c')  # 2.7+ only'a, b, c'>>> '{2}, {1}, {0}'.format('a', 'b', 'c')'c, b, a'>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence'c, b, a'>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated'abracadabra' >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')'Coordinates: 37.24N, -115.81W'>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)'Coordinates: 37.24N, -115.81W' >>> c = 3-5j>>> ('The complex number {0} is formed from the real part {0.real} '...  'and the imaginary part {0.imag}.').format(c)'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'>>> class Point(object):...     def __init__(self, x, y):...         self.x, self.y = x, y...     def __str__(self):...         return 'Point({self.x}, {self.y})'.format(self=self)...>>> str(Point(4, 2))'Point(4, 2) >>> coord = (3, 5)>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)'X: 3;  Y: 5' >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')"repr() shows quotes: 'test1'; str() doesn't: test2" >>> '{:<30}'.format('left aligned')'left aligned                  '>>> '{:>30}'.format('right aligned')'                 right aligned'>>> '{:^30}'.format('centered')'           centered           '>>> '{:*^30}'.format('centered')  # use '*' as a fill char'***********centered***********' >>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always'+3.140000; -3.140000'>>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers' 3.140000; -3.140000'>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}''3.140000; -3.140000' >>> # format also supports binary numbers>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)'int: 42;  hex: 2a;  oct: 52;  bin: 101010'>>> # with 0x, 0o, or 0b as prefix:>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010' >>> '{:,}'.format(1234567890)'1,234,567,890' >>> points = 19.5>>> total = 22>>> 'Correct answers: {:.2%}.'.format(points/total)'Correct answers: 88.64%' >>> import datetime>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)'2010-07-04 12:15:58' >>> for align, text in zip('<^>', ['left', 'center', 'right']):...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)...'left<<<<<<<<<<<<''^^^^^center^^^^^''>>>>>>>>>>>right'>>>>>> octets = [192, 168, 0, 1]>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)'C0A80001'>>> int(_, 16)3232235521>>>>>> width = 5>>> for num in range(5,12):...     for base in 'dXob':...         print '{0:{width}{base}}'.format(num, base=base, width=width),...     print...    5     5     5   101    6     6     6   110    7     7     7   111    8     8    10  1000    9     9    11  1001   10     A    12  1010   11     B    13  1011 >>> from string import Template>>> s = Template('$who likes $what')>>> s.substitute(who='tim', what='kung pao')'tim likes kung pao'>>> d = dict(who='tim')>>> Template('Give $who $100').substitute(d)Traceback (most recent call last):[...]ValueError: Invalid placeholder in string: line 1, col 10>>> Template('$who likes $what').substitute(d)Traceback (most recent call last):[...]KeyError: 'what'>>> Template('$who likes $what').safe_substitute(d)'tim likes $what'string.capitalize(word) 返回一个副本,首字母大写>>> string.capitalize("hello")'Hello'>>> string.capitalize("hello world")'Hello world' >>> string.split("asdadada asdada")['asdadada', 'asdada'] >>> string.strip("              adsd         ")'adsd'>>> string.rstrip("              adsd         ")'              adsd'>>> string.lstrip("              adsd         ")'adsd         ' string.swapcase(s) 小写变大写,大写变小写>>> string.swapcase("Helloo")'hELLOO' >>> string.ljust("ww",20)'ww                  '>>> string.rjust('ww',20)'                  ww'>>> string.center('ww',20)'         ww         'string.zfill(s, width)Pad a numeric string on the left with zero digits until the given width is reached. Strings starting with a sign are handled correctly.>>> string.zfill('ww',20)'000000000000000000ww'



转载与https://www.cnblogs.com/rollenholt/archive/2011/11/25/2263722.html




方法1: 用字符串的join方法
a = ['a','b','c','d']
content = ''
content = ''.join(a)
print content
方法2: 用字符串的替换占位符替换
a = ['a','b','c','d']
content = ''
content = '%s%s%s%s' % tuple(a)
print content
想要了解更多,请看python字符串连接
字符串截取
我们可以通过索引来提取想要获取的字符,可以把python的字符串也做为字符串的列表就更好理解


python的字串列表有2种取值顺序
1是从左到右索引默认0开始的,最大范围是字符串长度少1
s = 'ilovepython'
s[0]的结果是i


2是从右到左索引默认-1开始的,最大范围是字符串开头
s = 'ilovepython'
s[-1]的结果是n


上面这个是取得一个字符,如果你的实际要取得一段子串的话,可以用到变量[头下标:尾下标],就可以截取相应的字符串,其中下标是从0开始算起,可以是正数或负数,下标可以为空表示取到头或尾。


比如
s = 'ilovepython'
s[1:5]的结果是love
当使用以冒号分隔的字符串,python返回一个新的对象,结果包含了以这对偏移标识的连续的内容,左边的开始是包含了下边界,比如
上面的结果包含了s[1]的值l,而取到的最大范围不包括上边界,就是s[5]的值p


想要了解更多,请看python字符串截取
字符串替换
字符串替换可以用内置的方法和正则表达式完成。
1用字符串本身的replace方法:
a = 'hello word'
b = a.replace('word','python')
print b
2用正则表达式来完成替换:
import re
a = 'hello word'
strinfo = re.compile('word')
b = strinfo.sub('python',a)
print b
想要了解更多,请看python 字符串替换
字符串比较
cmp方法比较两个对象,并根据结果返回一个整数。cmp(x,y)如果X< Y,返回值是负数 如果X>Y 返回的值为正数。
sStr1 = 'strch'
sStr2 = 'strchr'
print cmp(sStr1,sStr2)##-1
字符串相加
我们通过操作符号+来进行字符串的相加,不过建议还是用其他的方式来进行字符串的拼接,这样效率高点。
原因:在循环连接字符串的时候,他每次连接一次,就要重新开辟空间,然后把字符串连接起来,再放入新的空间,再一次循环,又要开辟新的空间,把字符串连接起来放入新的空间,如此反复,内存操作比较频繁,每次都要计算内存空间,然后开辟内存空间,再释放内存空间,效率非常低。
sStr1 = 'strch'
sStr2 = 'strchr'
newstr = sStr1 + sStr2
print newstr
字符串查找
python 字符串查找有4个方法,1 find,2 index方法,3 rfind方法,4 rindex方法。
1 find()方法:
info = 'abca'
print info.find('a')##从下标0开始,查找在字符串里第一个出现的子串,返回结果:0


info = 'abca'
print info.find('a',1)##从下标1开始,查找在字符串里第一个出现的子串:返回结果3


info = 'abca'
print info.find('333')##返回-1,查找不到返回-1
2 index()方法:
python 的index方法是在字符串里查找子串第一次出现的位置,类似字符串的find方法,不过比find方法更好的是,如果查找不到子串,会抛出异常,而不是返回-1
info = 'abca'
print info.index('a')
print info.index('33')
字符串分割
字符串分割,可以用split,rsplit方法,通过相应的规则来切割成生成列表对象
info = 'name:haha,age:20$name:python,age:30$name:fef,age:55'
content = info.split('$')
print content
字符串翻转
通过步进反转[::-1]
a = 'abcd'
b = a[::-1]##[::-1]通过步进反转
print b
字符串编码
通过字符串的decode和encode方法
1 encode([encoding,[errors]]) 
#其中encoding可以有多种值,比如gb2312 gbk gb18030 bz2 zlib big5 bzse64等都支持。errors默认值为"strict",意思是UnicodeError。可能的值还有'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 和所有的通过codecs.register_error注册的值。
S.decode([encoding,[errors]]) 下面是字符串编码应用:
a = '你好'
b = 'python'
print a.decode('utf-8').encode('gbk')##decode方法把字符串转换为unicode对象,然后通过encode方法转换为指定的编码字符串对象
print b.decode('utf-8')##decode方法把字符串转换为unicode对象
字符串追加和拼接
通过字符串的占位符来进行字符串的拼接
#1 元组拼接
m = 'python'
astr = 'i love %s' % m
print astr


#2 字符串的format方法
m = 'python'
astr = "i love {python}".format(python=m)
print astr


#3 字典格式化字符串
m = 'python'
astr = "i love %(python)s " % {'python':m}
print astr
字符串复制
通过变量来进行赋值
fstr = 'strcpy'
sstr = fstr
fstr = 'strcpy2'
print sstr
字符串长度
通过内置方法len()来计算字符串的长度,注意这个计算的是字符的长度。
aa = 'afebb'
bb = '你'
print len(aa)
print len(bb)
字符串大小写
通过下面的upper(),lower()等方法来转换大小写
S.upper()#S中的字母大写 
S.lower() #S中的字母小写 
S.capitalize() #首字母大写 
S.istitle() #S是否是首字母大写的 
S.isupper() #S中的字母是否便是大写 
S.islower() #S中的字母是否全是小写 
字符串去空格
通过strip(),lstrip(),rstrip()方法去除字符串的空格
S.strip()去掉字符串的左右空格
S.lstrip()去掉字符串的左边空格
S.rstrip()去掉字符串的右边空格
字符串其他方法
字符串相关的其他方法:count(),join()方法等。
S.center(width, [fillchar]) #中间对齐
S.count(substr, [start, [end]]) #计算substr在S中出现的次数
S.expandtabs([tabsize]) #把S中的tab字符替换没空格,每个tab替换为tabsize个空格,默认是8个 
S.isalnum() #是否全是字母和数字,并至少有一个字符 
S.isalpha() #是否全是字母,并至少有一个字符 
S.isspace() #是否全是空白字符,并至少有一个字符
S.join()#S中的join,把列表生成一个字符串对象
S.ljust(width,[fillchar]) #输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。
S.rjust(width,[fillchar]) #右对齐 
S.splitlines([keepends]) #把S按照行分割符分为一个list,keepends是一个bool值,如果为真每行后而会保留行分割符。
S.swapcase() #大小写互换 


阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 喝啤酒打嗝怎么办 酒后老是打嗝怎么办 酒后一直打嗝怎么办 被动物咬伤怎么办 被猫狗挖伤咬伤怎么办 卡介苗接种失败怎么办 起脓包怎么办 卡介苗没打上怎么办 卡介苗化脓流血怎么办 卡介苗出脓破了怎么办 卡介苗反复化脓怎么办 卡介苗化脓洗澡怎么办 卡介苗没化脓怎么办 企业倒闭了贷款怎么办 开户银行倒闭怎么办 储户死亡存款怎么办 etc被盗刷怎么办 供应商拖欠发票怎么办 私人老板拖欠工资怎么办 小工厂拖欠工资怎么办 婚姻八字不合怎么办 生辰八字不合怎么办 夫妻不合怎么办 歪到脖子怎么办 怀孕记不清月经怎么办 头顶没头发怎么办 晚上睡觉噩梦怎么办 天生金鱼眼怎么办 吃蘑菇中毒怎么办 平菇吃了中毒怎么办 吃菌中毒怎么办 隆鼻手术不满意怎么办 富士康淡季怎么办 手术后血栓怎么办? 一把手打压副职怎么办 国有企业招工怎么办 国营企业怎么办招工 央企混改员工怎么办 被国资委收购后怎么办 事业单位转企业怎么办 宝宝不会写字怎么办