Python字符串常用处理方法

Python中的字符串方法

前言

Python是一门灵活的动态语言, 其中最重要的数据类型便是字符串, 这点对Unix-like系统来说十分有利。同时,python也为我们提供了许多有用的字符串方法,在此收集一些常用的,以便日常使用(以下版本都为python3)。

  1. 最基本的”构造“方法:str()
>>> a = 123
>>> type(a)
int
>>> type(str(a))
str
  1. 运算符
>>>a = '123'
>>>b = a * 2
>>>b
'123123'
>>>b + a 
'123123123'
>>>a in b
true
>>>b[3]
'123'
  1. 字符串连接:’’.join( list )
>>>a = 'a'
>>>b = 'b'
>>>''.join((a,b))
'ab'
  1. 字符串转列表:str.split(‘’)
#这个也可用于切割
>>>s = 'a.b.c'
>>>l = s.split('')
>>>l
['a', 'b', 'c']
  1. 字符串切割:str.strip(’’)
>>>s = '    abc     '
>>>l = s.strip(' ')
>>>l
'abc'
>>>l = s.rstrip(' ')
>>>l
'    abc'
  1. 字符串查找:str.find(‘’, [begin = 0 ,[,end = length(str)]] )
>>>s = 'how are you'
>>>s.find('are')
4
>>>s.find('gg')
-1
>>>s.find('are', 0, 3)
-1
  1. 格式化字符串:str.format()
#有无索引都可以,不过有索引的话会更清晰
>>> s = ' name : {0}, id : {1} ' .format('jack', '101')
'name : jack, id : 101'
>>>s = ' name : {1}, id : {0}'. format('101', 'jack')
‘name : jack, id : 101#有参数的形式则更好
>>> s = 'name : {name}, id : {id}'.format(name = 'jack', id = '101')
‘name : jack, id : 101
  1. 字符串代替:str.replace(str1, str2[, count = ])
#count 参数指定替换的最大次数
>>>s = '123n123n123n'
>>>s.replace('n', 'm')
'123m123m123m'
>>>s.replace('n', 'm', 1)
'123m123n123n'
  1. 字符串首尾判断:str.endswith(’ ‘) / str.startswith(’ ')
>>>s = '123-----------abc'
>>>s.endswith('abc')
True
>>>s.startswith('123')
True

常用差不多先这些,以后有看到新的再添加

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值