Python基础教程 | 第三章 字符串

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_width

head_format = '%-*s%*s'
format      = '%-*s%*.2f' 

print '-' * width
print head_format % (item_width, 'Item', price_width, 'Price')

print '-' * width

print 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):创建用于转换的转换表;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值