一些常用的字符串方法

  1. center 通过在两边填充字符(默认为空格)让字符串居中
    center(width, fillchar ) 指定的宽度 width 居中的字符串,fillchar 为填充的字符
>>> str = "[name,sex,class,degree]"
>>> str.center(40,'*')
'********[name,sex,class,degree]*********'
  1. find 检测是否包含在字符串中,如果包含则返回开始的索引值,否则返回-1。可以指定范围
>>> str = "[name,sex,class,degree]"
>>> str.find('name')
1
>>> str.find('name',3,9)
-1
>>> str.find('class',4)
10
  1. join 用于合并序列的元素
>>> s1 = '-'
>>> s2 = ''
>>> seq = ('r','e','s','t')
>>> s1.join(seq)
'r-e-s-t'
>>> s2.join(seq)
'rest'
>>> seq = ['1','2','3','4']
>>> s1 = '+'
>>> s1.join(seq)
'1+2+3+4'
>>> seq = [1, 2, 3, 4, 5]
>>> sep = '+'
>>> sep.join(seq) # 尝试合并一个数字列表 
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: sequence item 0: expected string, int found

可以发现,所合并的元素必须都是字符串。
4. split 其作用与join相反,用于将字符串拆分为序列。
如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格、制表符、换行符 等)处进行拆分。
格式:str.split(str="", num=string.count(str))
str --分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num – 分割次数。默认为 -1, 即分隔所有。

>>> str = 'this is a book'
>>> str.split()      #以空格为分隔符
['this', 'is', 'a', 'book']
>>> str.split('i',1)      #以i为分隔符,分隔1次
['th', 's is a book']
>>> str.split('i')        #以i为分隔符,分隔所有
['th', 's ', 's a book']
>>> str.split('s')        #以s为分隔符,分隔所有
['thi', ' i', ' a book']
  1. lower 返回字符串的小写版本。 特别是在查找一个人名时,大小写不一致会查不到,这个时候lower会很有用。
>>> seq = 'CONTUNE'
>>> seq.lower()
'contune'
>>> seq = 'CONTUNE'
>>> seq.lower()
'contune'
>>> name = 'Alice'
>>> names = ['alice','smith','andy']
>>> if name.lower() in names:print('found it!')
...
found it!
  1. upper 将字符串中的小写字母转为大写
>>> str = 'this is a book'
>>> str.upper()
'THIS IS A BOOK'
  1. replace 将指定子串都替换为另一个字符串,并返回替换后的结果
    语法:str.replace(old, new)
>>> str = '2019年研究生招生信息网'
>>> print(str)
2019年研究生招生信息网
>>> str.replace('2019','2020')
'2020年研究生招生信息网'
  1. strip 将字符串开头和末尾的空白(不包括中间的空白)删除,并返回删除后的结果。
    lstrip 删除左边的空白字符
    rstrip 删除右边的空白字符
>>> str ='      this is a book      '
>>> str.strip()
'this is a book' 
>>> str.lstrip()
'this is a book      '
>>> str.rstrip()
'      this is a book'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值