1. 基本字符串操作

标准序列操作:索引、分片、乘法、 成员资格、长度、最大最小值

>>> website = 'www.baidu.com'
>>> website[5]                 #索引
'a'
>>> website[10:2:-2]           #分片
'cuib'
>>> 2*website                  #乘法
'www.baidu.comwww.baidu.com'
>>> 'baidu' in website         #成员资格
True
>>> len(website)               #长度
13
>>> sorted(website)
['.', '.', 'a', 'b', 'c', 'd', 'i', 'm', 'o', 'u', 'w', 'w', 'w']

2. 字符串格式化:精简版

字符串格式化操作符:%

  • % 也可以用于求模;
  • 转换说明符:%s,s值会被格式化为字符串;
  • f 说明符类型:%n.mf,格式化为实数或浮点数,m为要保留的小数点位数,n为长度;
  • 使用 %% 可以在字符串里面包括%;
  • 使用方法:string % 值;值 可以是一个值,如一个字符串或数字,也可以使用多个值的元组字典.
>>> format = "Hello, %s! %s enough for ya? The temperature is %.2f."
>>> values = ('John', 'Hot', 30.134)   #使用元组
>>> print format % values
Hello, John! Hot enough for ya? The temperature is 30.13.
>>> format  ="Pi with three decimals: %.3f"
>>> from math import pi
>>> print format % pi
Pi with three decimals: 3.142 
  • 模板字符串
  • Template——从string库中调用;

    Template的实现方式是首先通过Template初始化一个字符串,这些字符串中包含了一个个key,通过调用substitutesafe_subsititute,将key值与方法中传递过来的参数对应上,从而实现在指定的位置导入字符串。这个方式的一个好处是不用像print ‘%s’之类的方式,各个参数的顺序必须固定。只要key是正确的,值就能正确插入。如果key少输入了一个怎么办呢?substitute是一个严肃的方法,如果有key没有输入,那就一定会报错。safe_substitute则不会报错,而是将$xxx直接输入到结果字符串中。
    - Template中有两个重要的方法:substitute 和 safe_substitute;这两个方法都可以通过获取参数返回字符串使用;它们可以把传递进来的关键字参数**xxx替换到 $**xxx ;

>>> from string import Template
>>> s = Template('$$a, glorious $b!')    #$ $中的一个是markdown语法不对多加的
>>> s.substitute(a = 'Apple', b = 'banada')
'Apple, glorious banada!'>>> s = Template("$$a, glorious $b")
>>> s.safe_substitute(a = 'Apple')
'Apple, glorious $b'
>>> s.safe_substitute(b = 'banana')
'$a, glorious banana'>>> s = '%s, glorious %s'
>>> values = ('slurm', 'slurm')
>>> print s % values
slurm, glorious slurm
  • 当替换字段是字符串的一部分时,参数名需用 {} 括起来;
>>> s = Template("It's ${x}tastic!")
>>> s.substitute(x = 'slurm')
"It's slurmtastic!">>> s = "It's %stastic!"
>>> print s % 'slurm'
It's slurmtastic!
  • 使用 $$ 在字符串中输入$符号;
  • 还可以使用字典变量提供值/名称对;

3. 字符串格式化:完整版

3.1 简单转换

>>> 'Price of eggs $%d' % 1.2   # %d 十进制
'Price of eggs $1'
>>> 'Hexadecimal price of eggs: %x' % 42   # %x 十六进制小写
'Hexadecimal price of eggs: 2a'
>>> from math import pi
>>> 'Pi: %.5f...' % pi          # %.xf 十进制浮点数
'Pi: 3.14159...'
>>> 'Using str: %s' % 42L       # %s 字符串(str)
'Using str: 42'
>>> 'Using repr: %r' % 42L      # %r 字符串(repr)
'Using repr: 42L'

3.2 字段宽度和精度

  • %n.mf,n为宽度,m为精度;
  • %.ms,m为字符串最大宽度;
>>> from math import pi
>>> print 'Pi: %10f' % pi
Pi:   3.141593
>>> print 'Pi: %20f' % pi
Pi:             3.141593
>>> print 'Pi: %20.5f' % pi
Pi:              3.14159    >>> print ' %.10s' % 'hello, world!'
hello, wor
  • 可以使用 * 代替宽度and/or精度,此时数值会从元组参数中读出;
>>> print '%0*.*f' % (10, 5, pi)
0003.14159

3.3 符号、对齐和0填充

  • 在字段宽度和精度前还可以添加一个“标表”,可以是 “0” “+” “-” “空格”;
  • 0 表示数字将会用0填充;
  • “+” 表示正数和负数都表示出符号;对齐正数、负数很有用;
  • “-” 用来左对齐数值;
  • “” 空格在正数前面加上空格;
>>> from math import pi
>>> '%010.5f...' % pi
'0003.14159...'
>>> print ('%+d' % 10) + '\n' + ('%+d' % -10)
+10
-10
>>> print '%-10.5f' % pi
3.14159
>>> print ('% 5d' % 10) +'\n' + ('% 5d' % -10)10-10
#使用给定的宽度打印格式化后的价格列表
width = input("what's your width: ")price_width = 15
item_width = width - price_widthhead_format = '%-*s%*s'
format      = '%-*s%*.2f' print '-' * width
print head_format % (item_width, 'Item', price_width, 'Price')print '-' * widthprint format %(item_width, 'Apple', price_width, 22.2)
print format %(item_width, 'Pear', price_width, 19.8)
print format %(item_width, 'Banada', price_width, 32.33)
print format %(item_width, 'Wine', price_width, 10)
print format %(item_width, 'Chocolate', price_width, 8.2)
print format %(item_width, 'Bread', price_width, 5.5)print '-'*width*************打印结果***************
what's your width: 35
-----------------------------------
Item                          Price
-----------------------------------
Apple                         22.20
Pear                          19.80
Banada                        32.33
Wine                          10.00
Chocolate                      8.20
Bread                          5.50
-----------------------------------

4. 字符串方法

4.1 find

  • 在一个较长的字符串中查找子字符串,并返回子字符串所在位置最左端的位置,如没没有找到则返回 -1
  • 使用方法:string_name.find(string, start, end)
>>> title = "How to read a book?"
>>> title.find('to')            #提供子字符串最左端的位置
4
>>> title.find('an')            #子字符串不存在时返回-1
-1
>>> title.find('read', 1)       #提供查询的起始位置
7
>>> title.find('read', 0, 7)    #提供查询的起始和结束位置,注意结束位置不包括在内
-1

4.2 join

  • 由于在队列中添加元素,仅仅适用于字符串
  • 使用方法:连接符.join(variable)
>>> numbers = [1, 2, 3, 4, 5]
>>> sep = '+'
>>> sep.join(numbers)
TypeError: sequence item 0: expected string, int found>>> numbers = ['1', '2', '3', '4', '5']  #仅适用于字符串
>>> '+'.join(numbers)
'1+2+3+4+5'>>> dirs = [' ', 'usr', 'bin', 'env']
>>> '/'.join(dirs)
' /usr/bin/env'>>> print 'C: ' + '\'.join(dirs)
SyntaxError: EOL while scanning string literal>>> print 'C: ' + '\\'.join(dirs)        #需要把 \ 转义
C:  \usr\bin\env

4.3 lower

  • 返回字符串的小写形式;
  • 使用方法:string.lower()
>>> name = 'Tom'
>>> name_list = ('john', 'lily', 'tom', 'jenny')
>>> if name.lower() in name_list:print 'Find it!'
Find it!    

4.4 title和capwords函数

>>> greeting = "that's a boy!"
>>> print greeting.title()
That'S A Boy!>>> import string
>>> string.capwords(greeting)
"That's A Boy!"

capwords函数功能:

  • 将每个单词首字母置为大写
  • 将每个单词除首字母外的字母均置为小写;
  • 将词与词之间的多个空格用一个空格代替
  • 其拥有两个参数,第二个参数用以判断单词之间的分割符,默认为空格。
>>> greeting = 'hELLO, wORLD!'
>>> import string
>>> string.capwords(s)
'Hello World!'
>>> string.capwords(greeting)
'Hello, World!'

4.5 replace

返回某字符串中所有匹配项被替换后得到的字符串

>>> 'this is a test'.replace('is', 'eez')
'theez eez a test'

4.6 split——join的逆方法

当不提供分隔符的时候,默认为空格、制表、换行等

>>> "1+2+3+4+equal+10".split('+')
['1', '2', '3', '4', 'equal', '10']
>>> "1 2 3 4 equal 10".split()
['1', '2', '3', '4', 'equal', '10']

4.7 Strip

  • 去除字符串两侧(不包括内部)的空格或指定的字符串;
  • 和lower()同时使用可以方便对比输入和存储的字符串;
>>>user_info = ['tom', ['tom', '12'], ['liming', '13'], ['lily', '11']]
>>>name = raw_input("what's your name: ")
>>>age = raw_input("what's your age: ")
>>>if [name.lower(), str(age)] in user_info:print "Found it"
>>>if [name.strip(), str(age)] in user_info:print "Hello " + name --------------------------------------------------
>>> setence = " * * * this's a test ! ! ! * * * "
>>> setence.strip(' !*')   #去除空格、!、*
"this's a test"
>>> setence = " * * * this's a test ! ! ! * * * "
>>> setence.strip('!*')    #去除!、*
" * * * this's a test ! ! ! * * * "
>>> setence = "* * * this's a test ! ! ! * * *"
>>> setence.strip('!*')    #去除!、*
" * * this's a test ! ! ! * * "
#从外往内逐个去除,如果最外层的字符包括在需要去除的字符中,则被去除;否则不被去除。

4.8 translate

translate:一一映射,每个字符只要出现都会被替换为对应的字符;
replace:是字符串替换, 字符串完整出现后被整体替换,replace的两个字符串参数长度可以不同。

>>> import string
#定义的翻译表table中的instr都会被对应替换为outstr中的字符
#从string中调用了maketrans函数
>>> instr = 'abcdef'
>>> outstr = '123456'
>>> table = string.maketrans(instr, outstr)
#tanslate把给定字符串按照翻译表table进行替换操作
>>> 'abcdef-123'.translate(table)
'123456-123'    

5. 第三章 小节

  • 字符串格式化:左右对齐、设定字符串宽度、精确度、增加符号(±)、左填充0;
  • 字符串方法

本章新函数


string.capwords(string1[, sep]):使用split函数分隔字符串string1(以sep为分隔符),使用capitalize函数将得到的各个单词的首字母大写,并且使用join函数以sep分隔符将各个单词连接起来;

string.maketrans(from, to):创建用于转换的转换表;


Python基础教程 | 第三章 字符串相关推荐

  1. python基础教程第3章——字符串

    1.字符串格式化 字符串格式化操作符%+转换标志+最小字段宽度+点后跟精度值+转换类型 String模块提供另外一种格式化方式 from string import Template s=Templa ...

  2. python基础教程第三版电子版百度云-《python基础教程第三版》高清版PDF免费下载...

    下载地址1:http://t.cn/EGxO1sW Python基础教程 第3版Python简明教程书籍 Python编程从入门到实践 灵程序设计丛书 <python基础教程第三版>高清版 ...

  3. python基础教程第三版电子版-《python基础教程第三版》PDF高清完整版-免费下载...

    <python基础教程第3版>高清PDF下载地址:http://t.cn/EGxO1sW Python基础教程 第3版Python简明教程书籍 Python编程从入门到实践 灵程序设计丛书 ...

  4. python基础教程第三版-《Python基础教程第三版》原版中英文PDF+代码+袁国忠(译)...

    <Python基础教程第3版>整本书的结构安排还是比较明显的.先是基础知识和python的基本数据类型和语言特性介绍,然后是面向对象的编程.之后介绍python的标准库以及相关主题的编程( ...

  5. python程序实例教程基础-python基础教程第三版源代码

    [实例简介] python基础教程第三版源代码 python基础教程第三版源代码 [实例截图] [核心代码] Beginning_Python_version3_SourceCode └── Begi ...

  6. python基本代码教程-python基础教程第三版源代码

    [实例简介] python基础教程第三版源代码 python基础教程第三版源代码 [实例截图] [核心代码] Beginning_Python_version3_SourceCode └── Begi ...

  7. python基础教程免费下载-Python基础教程第三版PDF电子书免费下载

    <Python基础教程(第3版)>是2018年人民邮电出版社出版的图书,作者是[挪]Magnus Lie Hetland.该书全面介绍了Python的基础知识和基本概念,包括列表.元组.字 ...

  8. python基础教程第三版和第二版选哪个-python基础教程 2版和3版哪个适合新手?!...

    python基础教程 2版和3版哪个适合新手? 现在学是学python3. 两者的差异发者本身影响并不大,个别语法细微的差比如python3的print数方式使用,一些常用模块的名称差异,一些机制的差 ...

  9. python基础教程第三版豆瓣-1024,程序媛/猿请查收!

    点击上方蓝字关注我们 节专享福利:1024程序员 本期活动,不仅有赠书福利,且有购书福利,图灵公司联合当当网特意为{印象python}读者们申请了一波购书福利.感兴趣的读者朋友,请下拉至文末,领取福利 ...

最新文章

  1. bmaplib vue 调用_Vue-cli3/4中使用AMap、BMap
  2. Java并发编程(十四)并发容器类
  3. Ubuntu 16.04安装Memcached(单机)
  4. 阿里巴巴开源 Sentinel,进一步完善 Dubbo 生态
  5. 本题要求实现函数输出n行数字金字塔。_练习5-3 数字金字塔 (15分)
  6. ContainerAllocator详解
  7. WCF添加服务失败一则
  8. 很久很久之前的一道面试题(老师的生日是那一天?)~
  9. 一款基于SSM框架技术的全栈Java web项目(已部署可直接体验)
  10. 爬取淘宝商家货物简单销售数据(销量,价格,销售地,货物名称)
  11. Windows下安装numpy
  12. 第三代酷睿i3处理器_【分享】Intel酷睿Core历代CPU插槽类型、架构、及常用主板大全...
  13. 无人机技术将从硬件创新转向自动化智能飞行
  14. php下载链接 迅雷下载,php实现把url转换迅雷thunder资源下载地址的方法
  15. Entity Framework Core系列教程-3为现有数据库生成实体模型
  16. 复利现值系数怎么用计算机计算,复利现值系数计算方法是怎样的?
  17. 调试程序路径“C:\Users\{用户名}\vsdbg\vs2017u5”无效
  18. bearer token头_BearerToken之JWT的介绍
  19. a session ended very soon after starting. check that the command in profile default is correct
  20. echarts动态滑动平均滤波

热门文章

  1. Machine Learning – 第2周(Linear Regression with Multiple Variables、Octave/Matlab Tutorial)
  2. PiXYZStudio:Revit 模型轻量化
  3. Python turtle绘图(星之卡比)
  4. 编码器 协议不公开_公开编码的3种后果
  5. 个人/团队/企业/组织申请计算机软件著作权的流程
  6. C语言实现zbuffer消隐算法,基于图像的重建,image-based reconstruction,音标,读音,翻译,英文例句,英语词典...
  7. Python PDF文件转Word格式
  8. 《多元统计分析与R语言》实验2【因子分析】
  9. 微信小程序父子组件通信详解
  10. 解决微信环境下无法通过链接唤起App Store、微信访问App Store 链接白屏问题