Python 第三章:使用字符串

第三章:使用字符串

所有标准序列操作都适用于字符串,但是字符串是不可变的,即所有的元素赋值和切片都是非法的。


##设置字符串的格式

  • 百分号
    类似于C语言中的经典函数printf:在%左边指定一个字符串(格式字符串),并在右边指定要设置其格式的值,可以使用单个值、元组和字典。
formats = 'Hello, %s. %s enough for ya ?'
values = ('World', 'Hot')
print(formats % values)

print("Hello, %s. %s enough for ya?" % ('World', 'Hot'))
  • 模板字符串
    每个替换字段都用花括号括起来,其中可能包含名称,还可能包含有关如何对相应的值进行转换和格式设置信息。
  • 字符串格式设置示例
width = int(input('Please enter width: '))

price_width = 10
item_width = width - price_width

header_fmt = '{{:{}}}{{: >{}}}'.format(item_width, price_width)
fmt = '{{:{}}}{{: >{}.2f}}'.format(item_width, price_width)

print('=' * width)

print(header_fmt.format('Item', 'Price'))

print('-' * width)

print(fmt.format('Apple', 0.4))
print(fmt.format('Pears', 0.5))
print(fmt.format('Cantaloupes', 1.92))
print(fmt.format('Dried Apricots (16 oz.)', 8))
print(fmt.format('Prunes (4 lbs.)', 12))

print('=' * width)
  • 字符串方法

1.center
通过在两边填充字符(默认为空格)让字符串居中

>>>"The Middle by Jimmy Eat World".center(39)
'     The Middle by Jimmy Eat World     '
>>>"The Middle by Jimmy Eat World".center(39,"*")
'*****The Middle by Jimmy Eat World*****'

2.find
在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1

>>>title = "Monty Python's Flying Circus"
>>>title.find('Monty')
0
>>>title.find('Python')
6
>>>title.find('Flying')
15
>>>title.find('Zirquss')
-1

注意:find返回的并非布尔值。
还可以指定搜索的起点和终点。

>>>subject = '$$$ Get rich now!!! $$$'
>>>subject.find('$$$',1)
20
>>>subject.find('!!!')
16
>>>subject.find('!!!', 0, 16)  #同时指定了起点和终点
-1

3.join
作用与split相反,用于合并序列的元素(所合并序列的元素必须是字符串)

>>>dirs = ' ', 'usr', 'bin', 'env'
>>>'/'.join(dirs)
' /usr/bin/env'
>>>print('C:' + '\\'.join(dirs))
C: \usr\bin\env

4.lower
返回字符串的小写版本

>>>'Trondheim Hammer Dance'.lower()
'trondheim hammer dance'

5.replace
将指定子串都替换为另一个字符串,并返回替换后的结果

>>>'This is a test'.replace('is', 'eez')
'Theez eez a test'

6.split
作用于join相反,用于将字符串拆分为序列

'This is a test'.replace('is', 'eez')
'Theez eez a test'
'1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
'Using the default'.split() #默认空格拆分
['Using', 'the', 'default']

7.strip
将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果。

>>>'      internal whitespace is kept        '.strip()
'internal whitespace is kept'
>>>'*** SPAM * for * everyone!!! ***'.strip('  *!') #还可在一个字符串参数中指定要删除的字符
'SPAM * for * everyone'

8.translate
replace一样替换字符串特定部分,但不同的是它只能进行单字符替换。优势在与能够同时替换多个字符。使用tanslate之前必须创建一个抓换表。

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

9.判断字符串是否满足特定的条件
很多都是以is打头如isspaceisdigitisupper,它们判断字符串是否具有特定的性质。如果字符串具备特定的性质,这些方法就返回True,否则返回False。

本章介绍新函数

函数描述
string.capword(s[, sep])使用split根据sep拆分s,将每项的首字母大写,再以空格为分隔符将它们合并起来
ascii(obj)创建指定对象的ASCII表示
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值