Python入门(3):使用字符串

字符串和元组一样,是不可变的。因此对字符串的项或分片赋值时不合法的。

1、字符串格式化

字符串格式化用%来实现。%的左侧放置一个格式化字符串(称为转换说明符),右侧放置希望被格式化的值。

Remark1: 若格式化字符串里包括百分号,则必须使用%%。

Remark2: 若需要转换的元组作为转换表达式的一部分存在,则必须把它用圆括号括起来。

基本的转换说明符包括以下部分:

1)%:标记转换说明符的开始。

2)转换标志(可选):- 表示左对齐;+ 表示在转换值之前加上正负号;""(空格)表示正数前保留空格;0 表示转换值若位数不够则用0填充。

3)最小字段宽度(可选):转换后的字符串至少应该具有该值制定的宽度。若是*,则宽度从值元组中读出。

4)点(.)后跟精度值(可选):若转换的是实数,精度值就表示出现在小数点后的位数。若转换的是字符串,那么该数字就表示最大字段宽度。若是*,则精度将会从元组中读出。

5)转换类型:

转换类型含义转换类型含义
d(或i)带符号的十进制整数f(或F)十进制浮点数
o不带符号的八进制g若指数大于-4或者小于精度值则和e相同,否则与f相同
u不带符号的十进制G若指数大于-4或者小于精度值则和E相同,否则与F相同
x不带符号的十六进制(小写)C单字符(接受整数或者单字符字符串)
X不带符号的十六进制(大写)r字符串(使用repr转换任意Python对象)
e科学计数法表示的浮点数(小写)s字符串(使用str转换任意Python对象)
E科学计数法表示的浮点数(大写)  
format='Hello, %s. %s enough for ya?'
values=('world','Hot')
print(format % values)                      #Hello, world. Hot enough for ya?

format='Pi with three decimals: %.3f'
from math import pi
print(format % pi)                          #Pi with three decimals: 3.142
print('Pi: %f...' % pi)                     #Pi: 3.141593...
print('Very inexact estimate of pi: %i' % pi)   #Very inexact estimate of pi: 3
print('%10f' % pi)                          #  3.141593
print('%10.2f' % pi)                        #      3.14
print('%.2f' % pi)                          #3.14
print('%010.2f' % pi)                       #0000003.14
print('%-10.2f' % pi)                       #3.14      

from string import Template
s=Template('$x,glorious $x!')
print(s.substitute(x='slurm'))              #slurm,glorious slurm!
s=Template("It's ${x}tastic!")
print(s.substitute(x='slurm'))              #It's slurmtastic!
s=Template('Make $$ selling $x!')
print(s.substitute(x='slurm'))              #Make $ selling slurm!
s=Template('A $thing must never $action.')
d={}
d['thing']='gentleman'
d['action']='show his socks'
print(s.substitute(d))                      #A gentleman must never show his socks.

print('%s plus %s equals %s' % (1,1,2))     #1 plus 1 equals 2
print('Price of eggs: $%d' % 42)            #Price of eggs: $42
print('Hexadecimal price of eggs: %x' %42)  #Hexadecimal price of eggs: 2a
print('%.5s' % 'Guido van Rossum')          #Guido
print('%.*s' % (5,'Guido van Rossum'))      #Guido
print(('% 5d' % 10)+'\n'+('% 5d' % -10))    #   10
                                            #  -10
print(('%+5d' % 10)+'\n'+('%+5d' % -10))    #  +10
                                            #  -10

2、字符串方法

字符串方法实在太多,这里只介绍些特别有用的。

0)下面是一些有用的字符串常量

string.digits:包含数字0-9的字符串

string.letters:包含所有字母(大写或小写)的字符串

string.lowercase:包含所有小写字母的字符串

string.printable:包含所有可打印字符的字符串

string.punctuation:包含所有标点的字符串

string.uppercase:包含所有大写字母的字符串

若可确定自己使用的是ASCII,则可在变量中使用ascii_前缀,例如string.ascii_letters。

1)find:该方法可在一个较长的字符串中查找子串,返回子串所在位置的最左端索引。若没有找到,则返回-1。

(注意,由起始和终止值指定的范围(第二和第三个参数)包含第一个索引,但不包含第二个索引。这是Python的惯例。)

2)join:用来连接序列中的元素,是split方法的逆方法。被连接的序列元素必须是字符串。

3)lower:返回字符串的小写字母版。和lower方法相关的有:title方法(将字符串转换为标题,即所有单词的首字母大写),string模块的capword函数。

4)replace:返回某字符串的所有匹配项均替换之后得到的字符串。

5)split:用来将字符串分割成序列,是join方法的逆方法。

6)strip:返回去除两侧(不包括内部)空格的字符串。

7)translate:和replace方法一样可替换字符串中的某些部分,但translate方法只处理单个字符,其优势在于可同时进行多个替换。 在使用translate转换之前,需先完成一张转换表,可使用str.maketrans函数完成。str.maketrans()接受两个参数:两个等长的字符串,表示第一个字符串中的每个字符都用第二个字符串中相同位置的字符替换。

#1)find
print('With a moo-moo here, and a moo-moo there'.find('moo'))   #7
title="Monty Python's Flying Circus"
print(title.find('Monty'))                      #0
print(title.find('Python'))                     #6
print(title.find('Ziruqss'))                    #-1
subject='$$$ Get rich now!!! $$$'
print(subject.find('$$$'))                      #0
print(subject.find('$$$',1))                    #20
print(subject.find('!!!'))                      #16
print(subject.find('!!!',0,18))                 #-1

#2)join
seq=['1','2','3','4','5']
sep='+'
print(sep.join(seq))                            #1+2+3+4+5
dirs='','usr','bin','env'
print('/'.join(dirs))                           #/usr/bin/env
print('C:'+'\\'.join(dirs))                     #C:\usr\bin\env

#3)lower
print('Trondheim Hammer Dance'.lower())         #trondheim hammer dance
name='Gumby'
names=['gumby','smith','jones']
if name.lower() in names: print('Found it!')    #Found it!
print("that's all folks".title())               #That'S All Folks
import string
print(string.capwords("that's all folks"))      #That's All Folks

#4)replace
print('This is a test'.replace('is','eez'))     #Theez eez a test

#5)split
print('1+2+3+4+5'.split('+'))                   #['1', '2', '3', '4', '5']
print('/usr/bin/env'.split('/'))                #['', 'usr', 'bin', 'env']
print('Using the default'.split())              #['Using', 'the', 'default']

#6)strip
print('  internal whitespace is kept  '.strip())        #internal whitespace is kept
names=['gumby','smith','jones']
name='gumby '
if name.strip() in names: print('Found it')             #Found it

#7)translate
table=str.maketrans('cs','kz')
print('this is an incredible test'.translate(table))    #thiz iz an inkredible tezt 

以上。参考书是Magnus Lie Hetland著的《Python基础教程(第2版·修订版)》Chapter 3。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值