python 字符串


python 字符串

注意:字符串都是不可变的
>>> web = 'http://www.baidu.org'
>>> web[-3:]
'org'
>>> web[-3:]='com'
Traceback (most recent call last):
  File "<pyshell#137>", line 1, in <module>
    web[-3:]='com'
TypeError: 'str' object does not support item assignment

-----------------------------------------------------------------

格式化操作

>>> format = 'hello,%s %s yyyyy!!'

>>> values =('qiao','chao')
>>> print format % values
hello,qiao chao yyyyy!!

>>> format = 'hello,%%100 %s yyyyy!!'
>>> values =('qiaochao')
>>> print format % values
hello,%100 qiaochao yyyyy!!
注意:如果需要格式化的字符串中包含%  需要使用 %% ,这样python就不会将%误认为是转换说明符了

>>> format = 'Pi with three decimals: %.3f'
>>> from math import pi
>>> print format % pi
Pi with three decimals: 3.142
注意:如果要格式化实数(浮点数),同时提供所需要的精度:一个句点再加上希望保留的小数位数。

---------------------------------------------------------------------

模板字符串

>>> from string import Template
>>> s = Template("Tt's ${x}tastic")
>>> s.substitute(x='slurm')
"Tt's slurmtastic"
注意:{}内部的可以替换,如果不加括号 写成$x 则替换这里

>>> s = Template("Tt's $$ ${x} tastic")
>>> s.substitute(x='slurm')
"Tt's $ slurm tastic"
注意:如果内部有 $ 符号,需要 $$ 来转义

字典变量替换 值/名称对
>>> s = Template("Tt's $$ $thing tastic $action hah")
>>> d={}
>>> d['thing']='qiao'
>>> d['action']='chao'
>>> s.substitute(d)
"Tt's $ qiao tastic chao hah"

-------------------------------------------------------------------------

>>> '%10f' %pi  --------------字段宽10
'  3.141593'
>>> '%10.2f' %pi  ----------------字段宽10 精度2
'      3.14'
>>> '%.3f' %pi  -------------------精度3
'3.142'

>>> '%.5s' % 'Guionas asds'
'Guion'

>>> '%.5s' % (5,'Guionas asds')

Traceback (most recent call last):
  File "<pyshell#170>", line 1, in <module>
    '%.5s' % (5,'Guionas asds')
TypeError: not all arguments converted during string formatting
>>> '%.*s' % (5,'Guionas asds')
'Guion'

注意:可以使用 * 作为字段宽度或者精度,此时数值会从元组参数中读出

-----------------------------------------------------------------------

在字段宽度和精度之前还可以放置一个“标表”,可以是零,加号,减号或者空格

>>> '%010.2f' %pi
'0000003.14'

>>> 010
8

注意:010开头不是八进制数,表示字段宽度10位,用0进行填补空位。

>>> '%-10.2f' % pi
'3.14      '
注意:减号用来左对齐数值

空白意味着在正数前加上空格,在需要对齐正负数时会很有用
>>> print ('% 5d' % 10) + '\n' +('% 5d' % -10)
   10
  -10

+号 表示不管是正数还是负数都标示出符号
>>> print ('%+5d' % 10) + '\n' +('%+5d' % -10)
  +10
  -10

-----------------------------------------------------------------------

>>> import string   
>>> string.digits     ---------------包含数字0-9
'0123456789'   
>>> string.letters     ------------- 包含所有字母(大小写)
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> string.lowercase   ------ 包含所有小写字母
'abcdefghijklmnopqrstuvwxyz'
>>> string.printable   --------------包含所有可打印字符的字符串
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.punctuation   --------------------包含所有标点符号
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.uppercase   --------------所有大写字母
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

------------------------------------------------------------------------

1.find 方法
在一个较长的字符串中查找子字符串,返回子串所在位置的最左端索引
>>> ss='asdasdjdsfsdfqwe'
>>> ss.find('asd')
0
>>> ss.find('qwe')
13
>>> ss.find('qiaoc')
-1
不存在时返回-1

>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$',1)    ---只提供起点
20
>>> subject.find('!!!')
16
>>> subject.find('!!!',0,16)  ---提供起点和结束点
-1
>>> subject.find('!!!',0,20)
16

2. join方法 
是split 的逆方法,用来在队列中添加元素
>>> seq = [1,2,3,4,5]
>>> sep='+'
>>> sep.join(seq)
Traceback (most recent call last):
  File "<pyshell#202>", line 1, in <module>
    sep.join(seq)
TypeError: sequence item 0: expected string, int found
注意:需要添加队列的元素必须都是字符串

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


3. lower方法
返回字符串的小写字母版
>>> 'asdWW TYY'.lower()
'asdww tyy'


4. replace 方法
返回某字符串的所有匹配项均被替换之后得到的字符串
>>> 'This is a test'.replace('is','eez')
'Theez eez a test'


5. split 方法
>>> '1=2=3=4=5'.split('=')
['1', '2', '3', '4', '5']
>>> 'user is a bitch'.split()
['user', 'is', 'a', 'bitch']
注意:如果不提供任何分隔符,程序会把所有空格作为分隔符(空格,制表,换行等)


6.strip 方法
返回去除2侧(不包括内部)空格的字符串
>>> '   asd we asd sd     '.strip()
'asd we asd sd'
>>> '****asd we asd sd*******'.strip('*')
'asd we asd sd'
注意:也可以去掉指定需要去除的字符,作为参数传入

7. translate 方法
和replace类似,但是只能处理单个字符,优势在于可以同时进行多个替换,有时候比replace效率高得多
在使用translate之前需要完成一张转换表,转换表中是以某字符替换某字符的对应关系,可以用string模块中的
maketrans函数就行
maketrans 函数接受2个参数:2个等长的字符串,表示第一个字符串中的每个字符都用第二个字符串中相同位置的字符替换

>>> from string import maketrans
>>> table=maketrans('cs','kz')
>>> 'wo ca is jsnas'.translate(table)
'wo ka iz jznaz'
>>> table=maketrans('s','m')
>>> 'wo ca is jsnas'.translate(table)
'wo ca im jmnam'

translate 第二个参数是可选的,这个参数是用来指定需要删除的字符
>>> 'wo ca is jsnas'.translate(table,' ')
'wocaimjmnam'

 
----------------------------------------------------------------------

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值