Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
#3.1基本字符串操作
>>> website = 'http://www.python.org'
>>> website[-3:]='com'Traceback (most recent call last):File "<pyshell#1>", line 1, in <module>website[-3:]='com'
TypeError: 'str' object does not support item assignment
#3.2 字符串格式化:精简版
>>> format = "Hello, %s. %s is enough for ya?"
>>> values = ('world', 'Hot')
>>> print format % values
Hello, world. Hot is enough for ya?
>>> format = "Pi with three decimals: %.3f"
>>> from math import pi
>>> print format % pi
Pi with three decimals: 3.142
#模板字符串
>>> from string import Template
>>> s = Template('$x, glorious $x!')
>>> s.substitute(x='slurm')
'slurm, glorious slurm!'
>>> s = Template("It's ${x}tastic!")
>>> s.substitute(x='slurm')
"It's slurmtastic!"
>>> s = Template("Make $$ selling $x!")
>>> s.substitute(x='slurm')
'Make $ selling slurm!'
>>> 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.'
>>> #saft_substitute不会因缺少值或不对使用$字符而出错.
>>> '%s plus %s equlas %s' % (1,1,2)
'1 plus 1 equlas 2'
>>> '%s plus %s equlas %s' % 1,1,2Traceback (most recent call last):File "<pyshell#24>", line 1, in <module>'%s plus %s equlas %s' % 1,1,2
TypeError: not enough arguments for format string
>>> '%s plus %s equlas %s' % 1,1,2 # Lacks parentheses!Traceback (most recent call last):File "<pyshell#25>", line 1, in <module>'%s plus %s equlas %s' % 1,1,2 # Lacks parentheses!
TypeError: not enough arguments for format string
#3.3 字符串格式化:完整版
#3.3.1简单转换
>>> 'Price of eggs: $%d' % 42
'Price of eggs: $42'
>>> 'Hexadecimal price of eggs: %x' % 42
'Hexadecimal price of eggs: 2a'
>>> from math import pi
>>> 'Pi: %f...' % pi
'Pi: 3.141593...'
>>> 'Very inexact estimate of pi: %i' % pi
'Very inexact estimate of pi: 3'
>>> 'Using str: %s' % 42L
'Using str: 42'
>>> 'Using repr: %r' % 42L
'Using repr: 42L'
#3.3.2字段宽度和精度
>>> '%10f' % pi
'  3.141593'
>>> '%10.2f' % pi
'      3.14'
>>> '%.2f' % pi
'3.14'
>>> '%.5s' % 'Guido van Rossum'
'Guido'
>>> '%.*s' % (5, 'Guido van Rossum')
'Guido'
#3.3.3符号, 对齐和0填充
>>> '%010.2f' % pi
'0000003.14'
>>> 010
8
>>> '%-10.2f' % pi
'3.14      '
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)F
SyntaxError: invalid syntax
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)10-10
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)F
SyntaxError: invalid syntax
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)10-10
>>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10)+10-10#代码清单3-1 字符串格式化演示样例
#3.4字符串方法
#string模块还包含一些不能作为字符串方式使用的常量和函数
>>> import string
>>> string.digits
'0123456789'
>>> string.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?

@[\\]^_`{|}~' >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' >>> string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' #3.4.1 find >>> 'With a moo-moo here. and a moo-moo there'.find('moo') 7 >>> title = "Monty Python's Flying Circus" >>> title.find('Monty') 0 >>> title.find('Python') 6 >>> titie.find('Flying') Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> titie.find('Flying') NameError: name 'titie' is not defined >>> title.find('Flying') 15 >>> title.find('Zirquss') -1 >>> subject = '$$$ Get rich now!!! $$$' >>> subject.find('$$$') 0 >>> subject.find('$$$', 1) 20 >>> subject.find('!!!') 16 >>> subject.find('!!!', 0, 16) -1 #3.4.2 join >>> seq = [1,2,3,4,5] >>> sep = '+' >>> sep.join(seq) Traceback (most recent call last): File "<pyshell#69>", line 1, in <module> sep.join(seq) TypeError: sequence item 0: expected string, int found >>> seq = ['1','2','3','4','5'] >>> sep.join(seq) '1+2+3+4+5' >>> dirs = '','usr','bin','env' >>> '/'.join(dirs) '/usr/bin/env' >>> print 'C:' + '\\'.join(dirs) C:\usr\bin\env #3.4.3 lower >>> 'Trondheim Hammer Dance'.lower() 'trondheim hammer dance' >>> if 'Gumby' in ['gumby','smith','jones']: print 'Found it!' >>> name='Gumby' >>> names=['gumby','smith','jones'] >>> if name.lower() in names: print 'Found it!' Found it! #标题转换 >>> "that's all folks".title() "That'S All Folks" >>> import string >>> string.capwords("that's all, folks") "That's All, Folks" #3.4.4 replace >>> 'This is a test'.replace('is','eez') 'Theez eez a test' #3.4.5 split >>> '1+2+3+4+5'.split('+') ['1', '2', '3', '4', '5'] >>> '/usr/bin/env'.split('/') ['', 'usr', 'bin', 'env'] >>> 'Using the default'.split() ['Using', 'the', 'default'] #3.4.6 strip 相当于Java 中的 String.trim() >>> ' internal whitespace is kept '.strip() 'internal whitespace is kept' >>> names = ['gumby','smith','jones'] >>> name = 'gumby' >>> if name in names: print 'Found it!' Found it! >>> '*** SPAM * for * everyone!!! ***'.strip(' *!') 'SPAM * for * everyone' #3.4.7 translate >>> from string import maketrans >>> table = maketrans('cs', 'kz') >>> len(table) 256 >>> table[97:123] 'abkdefghijklmnopqrztuvwxyz' >>> maketrans('','')[97:123] 'abcdefghijklmnopqrstuvwxyz' >>> table = maketrans('cs','kz') >>> 'this is an incredible test'.translate(table) 'thiz iz an inkredible tezt' >>> 'this is an incredible test'.translate(table,' ') 'thizizaninkredibletezt' #非英语字符串问题 table = maketrans('X','x') word = 'Xxx' print word.translate(table).lower() print u'Xxx'.lower() #小结 #本章介绍了字符串的两种很重要的使用方式 #字符串格式化: 求模操作符(%)能够用来将其它值转换为包含转换标志的字符串,比如%s. 它还能用来对值进行不同方式的格式化, #包含左右对齐, 设定字段宽度以及精度,添加符号(正负号)或者左填充数字0等. #字符串方法 有些很实用,比方split和join,有些则用得很少,比方istitle或capitalize. #本章的新函数 #string.capwords(s[, sep]) 使用split函数切割字符串s(以sep为分隔符),使用capitalize函数将切割得到的各单词首字母大写,而且使用join函数以sep为分隔符 #将各单词连接起来 #string.maketrans(from,to) 创建用于转换的转换表 #接下来学什么 列表, 字符串和字典是Python中最重要的3种数据类型.

代码清单3-1 字符串格式化演示样例

#e3-1
#使用给定的宽度打印格式化后的价格列表width = input('Plese enter width: ')price_width = 10
item_width = width - price_width;#减号(-1)用来左对齐数值
header_format = '%-*s%*s'
format = '%-*s%*.2f'print '=' * widthprint header_format % (item_width, 'Item', price_width, 'Price')print '-' * widthprint format % (item_width, 'Apples', price_width, 0.4)
print format % (item_width, 'Pears', price_width, 0.5)
print format % (item_width, 'Cantaloupes', price_width, 1.92)
print format % (item_width, 'Dried Apricots (16 oz.)', price_width, 8)
print format % (item_width, 'Prunes (4 lbs.)', price_width, 12)print '=' * width#python e3-1.py
#Plese enter width: 35
#===================================
#Item                          Price
#-----------------------------------
#Apples                         0.40
#Pears                          0.50
#Cantaloupes                    1.92
#Dried Apricots (16 oz.)        8.00
#Prunes (4 lbs.)               12.00
#===================================

转载于:https://www.cnblogs.com/brucemengbm/p/6978736.html

Python基础教程之第3章 使用字符串相关推荐

  1. python可以处理多大的数据_科多大数据之Python基础教程之Excel处理库openpyxl详解...

    原标题:科多大数据之Python基础教程之Excel处理库openpyxl详解 科多大数据小课堂来啦~Python基础教程之Excel处理库openpyxl详解 openpyxl是一个第三方库,可以处 ...

  2. 什么是python基础教程-python基础教程之python是什么?概念解析

    Python,是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum于1989年发明,第一个公开发行版发行于1991年. Python是纯粹的自由软件, 源代码和解释器CP ...

  3. python的excell库_扣丁学堂Python基础教程之Excel处理库openpyxl详解

    扣丁学堂Python基础教程之Excel处理库openpyxl详解 2018-05-04 09:49:49 3197浏览 openpyxl是一个第三方库,可以处理xlsx格式的Excel文件.pipi ...

  4. python pymysql cursors_老雷python基础教程之pymysql学习及DB类的实现

    老雷python教程之pymysql学习及DB类的实现 CREATE TABLE `sky_guest` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` ...

  5. python画简单图形-python基础教程之turtle的简单绘图

    https://www.xin3721.com/eschool/pythonxin3721/ 接触python,就发现python是一门很有趣的课程.往往只需要利用几行简单的代码,就能绘制出简单漂亮的 ...

  6. python基础教程是什么-python基础教程之python是什么?

    Python是著名的"龟叔"Guido van Rossum在1989年圣诞节期间,为了打发无聊的圣诞节而编写的一个编程语言.本文引用地址:http://www.eepw.com. ...

  7. Python基础教程之Matplotlib-基础绘图

    最近想自学一些数据可视化相关的工具,首先想到了Python,于是自己写一些文章,把学习成果和问题贴出来,方便自己后续查询.之前有断断续续学习过一些Python的基础语法,所以直接从Matplotlib ...

  8. Python基础教程之Python简介

    #「笔耕不辍」–生命不息,写作不止# 1. Python是什么? (1)在介绍Python之前,先和大家聊一聊什么是编程语言.大家或许都知道,要让计算机为我们干活,就需要给计算机下指令,那么编程语言就 ...

  9. hello python的代码,python基础教程之Hello World!

    Python命令行 假设你已经安装好了Python, 那么在Linux命令行输入: 代码如下: $python 将直接进入python.然后在命令行提示符>>>后面输入: 代码如下: ...

最新文章

  1. OpenCV中图像旋转(warpAffine)算法的实现过程
  2. 原来 CPU 为程序性能优化做了这么多
  3. R语言IQR函数计算四分位数范围IQR(Interquartile Range)实战
  4. NET(C#)连接各类数据库-集锦
  5. \r与\n的区别,以及\r\n的用法
  6. 下列说法正确的是( )
  7. RowTime field should not be null, please convert it to a non-null long value.
  8. Apache配置(转载)
  9. 介绍开源的.net通信框架NetworkComms
  10. halcon图片上传到mysql_C# 10个线程并发执行Halcon图像算法 报“尝试读取或写入受保护的内存。这通常指示其他内存已损坏。”...
  11. 使用vue+elementUI+springboot创建基础后台增删改查的管理页面--(1)
  12. linux系统 (实验二)实验楼的课程笔记
  13. 【图像融合】基于matlab curvelet变换图像融合(评价指标)【含Matlab源码 781期】
  14. 使用devcon禁用启用网卡
  15. Springboot内置tomcat优化
  16. SMA连接器与BNC连接器用途有什么不同
  17. Unity使用tolua框架教程: LuaFramewrk
  18. 小程序 获取今天日期 星期几 不墨迹就是快
  19. KeyShot 实时光线追踪三维渲染软件
  20. 高级计算机软考科目,软考高级中哪个科目好考

热门文章

  1. 数据结构之图:有向图的拓扑排序,Python代码实现——26
  2. 十一、加权线性回归案例:预测鲍鱼的年龄
  3. LeetCode 214. 最短回文串(字符串哈希)
  4. LeetCode 1319. 连通网络的操作次数(BFS/DFS/并查集)
  5. LeetCode 1037. 有效的回旋镖
  6. LeetCode 434. 字符串中的单词数
  7. 程序员面试金典 - 面试题 10.03. 搜索旋转数组(二分查找)
  8. LeetCode 493. 翻转对(归并排序)
  9. java 动态队列_RabbitMq之动态修改队列参数
  10. win10win键无反应_台式电脑开机主机没反应怎么办 电脑开机主机没反应解决【详解】...