当前位置:Gxlcms > Python > python中字符串的几个方法的详细说明

python中字符串的几个方法的详细说明

时间:2021-07-01 10:21:17 帮助过:74人阅读

字符串格式化

  1. >>> '%s plus %s equals %s' % (1,1,2)
  2. '1 plus 1 equals 2'

字段的宽度和精度

*字段宽度是转换后的值所保留的最小字符个数,精度(对于数字)是包含的小数位数,或者(对于字符)转换后的值所能包含的最大字符数

  1. >>> from math import pi
  2. >>> '%10f' % pi
  3. ' 3.141593'
  4. >>> from math import pi
  5. >>> '%10f' % pi #字段宽10
  6. ' 3.141593'
  7. >>> '%10.2f' % pi #字段宽10,精度2
  8. ' 3.14'
  9. >>> '%.2f' % pi #精度2
  10. '3.14'
  11. >>> '%.5s' % 'My name is ningsi'
  12. 'My na'
  13. >>> '%.*s' % (5,'My name is ningsi')
  14. 'My na'

符号、对齐和0填充

  1. >>> '%010.2f' % pi #用0填充
  2. '0000003.14'
  3. >>> '%-10.2f' % pi #左对齐
  4. '3.14 '
  5. >>> print ('% 5d' % 10)+'\n'+('%5d' % -10)
  6. 10
  7. -10
  8. >>> print ('%+5d' % 10)+'\n'+('%+5d' % -10)
  9. +10
  10. -10

字符串的方法

find 查找子字符串

  1. >>> N='ning si de shu de'>>> N.find('de')8
  2. >>> N.find('dee')-1
  3. >>> N.find('de',9,16) #范围包含第一个索引不包含第二个-1

join 是split方法的逆方法

  1. >>> s=['1','2','3','4']
  2. >>> q.join(s)
  3. '1+2+3+4'
  4. >>> p='','usr','bin','env'
  5. >>> '/'.join(p)
  6. '/usr/bin/env'>>> print 'C:'+'\\'.join(p)
  7. C:\usr\bin\env

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

  1. >>> 'My name is ningsideshu'.lower()
  2. 'my name is ningsideshu'
  3. >>> if 'name' in ['my','Name','is']:print 'Found it!'
  4. >>> if 'my' in ['my','Name','is']:print 'Found it!'
  5. Found it!

replace 替换

  1. >>> 'This is a pen'.replace('pen','apple')'This is a apple'

split 将字符串分割成序列

  1. >>> '1+2+3+4+5'.split('+')
  2. ['1', '2', '3', '4', '5']
  3. >>> '/usr/bin/env'.split('/')
  4. ['', 'usr', 'bin', 'env']
  5. >>> 'Using the default'.split() #默认所有空格作为分隔符(空格、换行等)
  6. ['Using', 'the', 'default']

strip 返回去除两侧空格(或指定字符)的字符串 (另外:lstrip,rstrip)

  1. >>> ' My name is Nsds '.strip()'My name is Nsds'>>> ' *My name is Nsds * '.strip(' *')'My name is Nsds'

translate 替换,与replace不同的是,可以替换单个字符(字符串中的某些部分)

  1. >>> from string import maketrans
  2. >>> N=maketrans('ns','mf')
  3. >>> 'My name is ningsideshu'.translate(N)
  4. 'My mame if mimgfidefhu'
  5. >>> 'My name is ningsideshu'.translate(N,'M') #第二个参数指定需要删除的字符
  6. 'y mame if mimgfidefhu'

模版字符串

  1. >>> from string import Template
  2. >>> s=Template('$x. name $x!')
  3. >>> s.substitute(x='hello')
  4. 'hello. name hello!'
  5. >>> s=Template("It't ${x}tastic!")
  6. >>> s.substitute(x='slurm')
  7. "It't slurmtastic!"
  8. >>> s=Template("It't ${x}tastic${y}!")
  9. >>> s.substitute(x='slurm',y='a')
  10. "It't slurmtastica!"
  11. >>> s=Template('A $thing must never $action.')
  12. >>> d={}
  13. >>> d['thing']='gentleman'
  14. >>> d['action']='show his socks'
  15. >>> s.substitute(d)
  16. 'A gentleman must never show his socks.'

以上就是python中字符串的几个方法的详细说明的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行