Python中的字符串方法
前言
Python是一门灵活的动态语言, 其中最重要的数据类型便是字符串, 这点对Unix-like系统来说十分有利。同时,python也为我们提供了许多有用的字符串方法,在此收集一些常用的,以便日常使用(以下版本都为python3)。
- 最基本的”构造“方法:str()
>>> a = 123
>>> type(a)
int
>>> type(str(a))
str
- 运算符
>>>a = '123'
>>>b = a * 2
>>>b
'123123'
>>>b + a
'123123123'
>>>a in b
true
>>>b[:3]
'123'
- 字符串连接:’’.join( list )
>>>a = 'a'
>>>b = 'b'
>>>''.join((a,b))
'ab'
- 字符串转列表:str.split(‘’)
#这个也可用于切割
>>>s = 'a.b.c'
>>>l = s.split('')
>>>l
['a', 'b', 'c']
- 字符串切割:str.strip(’’)
>>>s = ' abc '
>>>l = s.strip(' ')
>>>l
'abc'
>>>l = s.rstrip(' ')
>>>l
' abc'
- 字符串查找: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
- 格式化字符串: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’
- 字符串代替:str.replace(str1, str2[, count = ])
#count 参数指定替换的最大次数
>>>s = '123n123n123n'
>>>s.replace('n', 'm')
'123m123m123m'
>>>s.replace('n', 'm', 1)
'123m123n123n'
- 字符串首尾判断:str.endswith(’ ‘) / str.startswith(’ ')
>>>s = '123-----------abc'
>>>s.endswith('abc')
True
>>>s.startswith('123')
True
常用差不多先这些,以后有看到新的再添加