「学习笔记」字符串

    (一)字符串切片

>>> str1 = 'abcdef'
>>> str1[:3]
'abc'
>>> str1[3:]
'def'

>>> str1[:3] + '插入' + str1[3:]
'abc插入def'

  (二)字符串的方法

#capitalize
>>> str1 = 'test'
>>> str1.capitalize()  #首字符改为大写
'Test'
>>> str1
'test'

#casefold
>>> str2 = 'ABCDEFG'
>>> str2.casefold()  #所有字符变为小写
'abcdefg'
>>> str2
'ABCDEFG'

#center:左右填充n个字符
>>> str2.center(40)  #左右都填充40个字符
'                ABCDEFG                 '

#count
>>> str1 = 'I am a test string hhh'
>>> str1.count(' ')  #指定字符串出现次数
5
>>> str1.count(' ',3)  #指定位置
4

#endswith
>>> str1.endswith('string',0,18)  #是否以指定字符串结尾
True
>>> str1.endswith('h')
True

#expandtabs
>>> str2
'a\tb\t'
>>> str2.expandtabs()  #将tab符号(\t)转换为空格,默认为8个空格
'a       b       '
>>> str2.expandtabs(1)
'a b '

#find
>>> str1.find('aaa')   #查找指定字符串是否在字符串中,若无返回-1,若有返回对应索引值,rfind从右边开始找
-1
>>> str1.find('hhh')
19

#index:跟find一样,不过如果不在会返回异常

#join
>>> str3
'你好呀'
>>> str3.join('111')
'1你好呀1你好呀1'

#lstrip() 去掉左边的空格
#rstrip() 去掉末尾的空格

#partition
>>> str4 = 'I love you'
>>> str4.partition('love')
('I ', 'love', ' you')
>>> str4.replace('love','hate')
'I hate you'

#split
>>> str4.split()  #默认以空格切片字符串
['I', 'love', 'you']

#strip
>>> str5
'    test        '
>>> str5.strip()   #默认去掉前面和后面的所有空格
'test'
>>> str5.strip('t')
'    test        '
>>> str4.strip('I')
' love you'

#swapcase
>>> str4.swapcase()
'i LOVE YOU'

#translate
>>> str4.translate(str.maketrans('you','who'))  #相当于replace,y替换w,o替换h,u替换o
'I lhve who'
>>> str.maketrans('you','who')
{121: 119, 111: 104, 117: 111}

  (三)字符串的格式化:按统一规格输出

  • replacement字段:{}
  • format:位置参数(0,1),关键字参数(a,b)(位置参数要在关键字参数之前)
>>> "{0} love {1}".format("I","you")
'I love you'
>>> "{a} love {b}".format(a="I",b="you")
'I love you'
>>> "{0} love {b}".format("I",b="you")
'I love you'
>>> "{{0}} and {0}".format("test")
'{0} and test'

  

>>> '{0:.1f}{1}'.format(27.658,"GB")   #冒号表示格式化符号的开始,留一位小数,f是机器码
'27.7GB'
  • 格式化符号
>>> '%c' % 51  #格式化字符及acill码
'3'
>>> '%c %c %c' % (100,101,102)  #使用元组方式输入数据
'd e f'

>>> '%s' % 98  #格式化字符串
'98'

>>> '%d + %d = %d' % (1,2,1+2)  #格式化整数
'1 + 2 = 3'

#格式化操作辅助命令
>>> '%.1f' % 23
'23.0'
>>> '%10.1f' % 23  #10为宽度,1为精确到第几位
'      23.0'
>>> '%-10.1f' % 23   #-用于左对齐
'23.0      '
>>> '%+10.1f' % 23   #在正数前显示+
'     +23.0'

#在八进制数前显示0o,在十六进制数前显示‘0x’
>>> '%#o' % 10  #八进制
'0o12'
>>> '%o' % 10
'12'
>>> '%#x' % 100  #十六进制
'0x64'
>>> '%x' % 100
'64'

#0:显示的数字前填充0代替空格
>>> '%010d' % 5
'0000000005'
>>> '%-010d' % 5
'5         '

  

posted @ 2019-01-18 11:25  半枫在努力  阅读(203)  评论(0)    收藏  举报