设为首页 收藏本站
查看: 814|回复: 0

[经验分享] python学习笔记4——第三章 字符串

[复制链接]

尚未签到

发表于 2017-5-7 10:58:57 | 显示全部楼层 |阅读模式
  第三章 字符串
  1. 字符串不可修改,无法进行分片赋值

>>> print "Hello %s " %('test')   #%表示需替代的位置,s表示类型
Hello test
>>> print "Hello %s" %'test'   #去掉括号也可
Hello test
>>>
>>> print "Hell %%s %s" %'test'   #%%输出%
Hell %s test
>>> from math import pi
>>> print "Pi with three decimals: %.3f" %pi           #.3表示希望保留的小数位数,f表类型
Pi with three decimals: 3.142

  模板字符串  string--Template---substitute

>>> #模板字符串
>>> from string import Template
>>> s = Template('$x. glorious $x!')
>>> s.substitute(x='slurm')
'slurm. glorious slurm!'
>>>
>>> #如果替换字段是单词的一部分,需要加{}
>>> s = Template("It's ${x}ful")
>>> s.substitute(x='beauti')
"It's beautiful"
>>>
>>> #使用字典变量,提供值/名对
>>> s = Template("A $thing must never $action.")
>>> d = {}
>>> d['thing'] = 'gentleman'
>>> d['action'] = 'show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks.'
>>>
  2. 字符串格式化
  (1)基本

>>> '%s plus %s equals %s' %(1, 1, 2)                #使用元组替代,注意不能丢掉括号
'1 plus 1 equals 2'
>>> 'Price of eggs: $%d' %42  # d 和 i 表带符号的十进制数
'Price of eggs: $42'
>>> 'Hexadecimal price of eggs $%x' %42  #x不带符号的十六进制(小写),X大写
'Hexadecimal price of eggs $2a'
>>> from math import pi
>>> 'Pi: %f...' %pi  #f/F十进制浮点数
'Pi: 3.141593...'
>>> 'Very inexact estimate of pi: %i' %pi #i带符号的十进制数
'Very inexact estimate of pi: 3'
>>> 'Using str: %s' %42L  #s字符串(str),r字符串(repr)
'Using str: 42'
>>> 'Using str: %r' %42L   #r字符串(repr)
'Using str: 42L'
  (2)字段宽度和精度

>>> #宽度:转换后的值所保留的最小字符个数
>>> #精度:应包含的小数位数(数字),或转换后的最大字符个数(字符串)
>>> '%10f' %pi   #字段宽10
'  3.141593'
>>> '%10.2f' %pi #字段宽10,精度(小数位)2
'      3.14'
>>> '%.2f' %pi   #精度2
'3.14'
>>> '%.5s' % 'Hello world'  #精度5,对于字符串来说,就是最多五个字符
'Hello'
>>> '%.*s' % (5, 'Hello world')  #用*表示精度,值在元组中
'Hello'
  (3)符号、对齐、0填充——在字段宽度和精度之前可放“标表”,该标表可以使0、+、-、空格

>>> '%010.2f' %pi  #0填充
'0000003.14'
>>> '%-10.2f' %pi  #左对齐
'3.14      '
>>> print('% 5d' %10) + '\n' + ('%5d' %-10)  #空格,在正数前加空白,方便与负数对齐,貌似不加也没问题??

10
-10
>>> print('%+5d' %10) + '\n' + ('%+5d' %-10)  #对正负数均标出符号
+10
  完整示例

#使用给定的宽度打印格式化后的价格列表
width = input('Please enter width: ')
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'   #-左对齐,*宽度,s字符串
content_format = '%-*s%*.2f'
print '=' * width
print header_format %(item_width, 'Item', price_width, 'Price')
print '-' * width
print content_format %(item_width, 'Apples', price_width, 0.4)
print content_format %(item_width, 'Pears', price_width, 0.5)
print content_format %(item_width, 'Cantaloupes', price_width, 1.92)
print content_format %(item_width, 'Dried Apricots(16 oz.)', price_width, 8)
print content_format %(item_width, 'Prunes(4 lbs.)', price_width, 12.3333333)
print '=' * width
#运行结果
Please enter width: 35
===================================
Item                          Price
-----------------------------------
Apples                         0.40
Pears                          0.50
Cantaloupes                    1.92
Dried Apricots(16 oz.)         8.00
Prunes(4 lbs.)                12.33
===================================
  3. 字符串方法

>>>#find()子串所在位置的最左端索引
>>> s = "Hello, how are you? Hello, I'm fine"
>>> s.find("Hello")         #in只能查找单个字符,而find可查找一个子串
0
>>> s.find("Hello", 1)     #提供查找的起始点
20
>>> s.find("you", 2, 16) #提供查找的起始点和结束点,其中包括起始索引,不包括结束索引
-1                                   #-1代表未找到
>>> s.find("you", 2, 20) #提供查找的起始点和结束点,其中包括起始索引,不包括结束索引
15
>>> #join()添加元素来连接列表,只能是字符串
>>> seq = ['1','2','3','4','5']
>>> joi = '+'
>>> joi.join(seq)
'1+2+3+4+5'
>>>
>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>>

>>> #lower()返回字符串小写字母
>>> "I'M A DOCTOR!".lower()
"i'm a doctor!"
>>>
>>> if 'GUMBY'.lower() in ['gumby', 'smith', 'jones']: print 'Found it!'
Found it!
>>> #title()单词首字母大写
>>> "that's all folks".title()
"That'S All Folks"
>>>
>>> string模块的capwords()
>>> import string
>>> string.capwords("that's all, folks")
"That's All, Folks"
>>> #replace()替换
>>> 'This is a test'.replace('is', "isn't")
"Thisn't isn't a test"
>>> #split()分割,join()的逆方法
>>> 'Using the defalut'.split()
['Using', 'the', 'defalut']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

>>> #strip()去除两侧空格
>>> "     Hello world   test   ".strip()
'Hello world   test'
>>> #也可指定需要去除的字符,将其列为参数即可,但是只去除两侧的字符
>>> '*** Hello * world ***!!!'.strip('*!')
' Hello * world '
#translate()同replace()一样,不过只能处理单个字符
#string模块中的maketrans()函数
>>> from string import maketrans
>>> table = maketrans('cs', 'kz')   #将c换为k,s换为z
>>> len(table)
256
>>> table[97:123]
'abkdefghijklmnopqrztuvwxyz'
>>> 'this is an incredible test'.translate(table)  #使用table作参数
'thiz iz an inkredible tezt'

  总结:内容仍然简单,不过效率低,一点东西花了好长时间,需改善。
  用到的函数
  string.capsword(s[,seq])  #以seq分隔字符后,大写第一个字母,再用seq连接
  string.maketrans(from, to)

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-374120-1-1.html 上篇帖子: python 两列表比较返回匹配列表 下篇帖子: python学习笔记10——构造方法、属性和迭代器
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表