python学习-字符串操作

来源:互联网 发布:单片机数字式温度计 编辑:程序博客网 时间:2024/05/17 23:31

记录几个平时使用较少的方法,加深印象

1、string.capatize(self)

  • 对首字母进行大写转换
name = 'yanzu wu'print(name.capitalize())

输出

Yanzu wu

2、string.center(self, width, fillchar)

  • 输出一个长度为width的字符串,string居中,其余使用fillchar填充
name = 'yanzu wu'print(name.center(30, '='))

输出

===========yanzu wu===========

3、string.format(self, args, kwargs)

  • 格式化字符串输出
msg = 'hello {name},welcome to {location}'msg2 = 'hello {0},welcome to {1}'print(msg.format(name = 'wuyanzu', location = 'shanghai'))print(msg2.format('wuyanzu', 'shanghai'))

输出

hello wuyanzu,welcome to shanghai
hello wuyanzu,welcome to shanghai

4、string.find(self, sub, start, end)

  • 输出找到的字符的位置(多个只返回第一个),未找到则返回-1。sub为指定的字符串,start、end可不填,指定搜索范围的起始和结束为止。
name = 'yanzu wu'print(name.find('u'))print(name.find('e'))

输出

4
-1

0 0
原创粉丝点击