python学习笔记7(使用字符串)

时间:2023-03-09 15:56:40
python学习笔记7(使用字符串)

一、字符串格式化,在%左侧放置一个字符串,右侧放置希望格式化的值。

>>> format = 'Hello,%s,%s enough for ya?'
>>> values = ('world','Hot')
>>> print format % values
Hello,world,Hot enough for ya?
>>> '%s plus %s equals %s' % (1,2,3)       # 如果需要转换的元组作为转换表达式的一部分存在,则需将它用圆括号括起来。
'1 plus 2 equals 3'

1、简单转换

>>> 'price of eggs: $%d' % 42
'price of eggs: $42'

2、字段宽度与精度

>>> from math import pi
>>> '%10.2f' % pi # 字段宽为10,精度为2
' 3.14'

二、字符串方法

find  在长字符串中查找子字符串,返回子串所在位置的最左端索引,如果没有找则返回-1

>>> 'with a moo-moo here,and a moo-mo0 there'.find('moo')
7
>>> subject = "$$$ get rich now! $$$"
>>> subject.find('$$$')
0

join 用来在队列中添加元素            (非常重要的字符串方法

>>> dirs = '','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> seq = ['','',''] # 要添加的队列都必需是字符串
>>> sep = '+'
>>> sep.join(seq)
'1+2+3'

lower  返回字符串的小写字母版

>>> 'Please Enter your name'.lower()
'please enter your name'

replace   返回某字符串匹配项被替换后得到字符串

>>> 'This is a test'.replace('is','AAA')
'ThAAA AAA a test'

spilt  用来将字符串分割成序列,它是join逆方法              (非常重要的字符串方法

>>> '1+2+3'.split('+')
['', '', '']
>>>
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>>
>>> 'using the default'.split() # 如果未提供分隔符,程序会把所有空格作为分隔符
['using', 'the', 'default']