Python中的str
python中字符串的常用方法
str_lst = [
('元素替换',),
('字符串切片',),
('字符串分割',),
('字符串连接',),
('元素计数',),
('寻找元素',),
('判断字符串的开头与结尾',),
('字符串的大小写转换',),
('移除字符串首尾指定字符',),
('判断字符串的组成',),
('练习',),
]
元素替换
>>>s = 'success'
>>>s.replace('c', 'm', 1)
'sumcess'
字符串切片
>>>s = '123456789'
>>>s[::2]
'13579'
>>>s[::-2]
'97531'
字符串分割
>>>s = 'succ ess'
>>>s.split()
['succ', 'ess']
字符串连接
>>>s = ''
>>>s_lst = ['succ', 'ess']
>>>s.join(s_lst)
'success'
>>>'6' + '6'
'66'
>>>'=' * 4
'===='
>>>'%s: %d' % ('age', 18)
'age: 18'
>>>'{name}|{pwd}'.format(name='hopen', pwd='123456')
'hopen|123456'
元素计数
>>>s = 'success'
>>>s.count('s')
3
寻找元素
>>>s = 'success'
>>>s.find('s', 1)
5
>>>s.find('f')
-1
>>>s.index('s')
0
>>>s.index('f')
valueerror: substring not found
判断字符串的开头与结尾
>>>s = 'success'
>>>s.startswith('suc')
true
>>>s.endswith('ess')
true
字符串的大小写转换
>>>s = 'success'
>>>s.upper()
'success'
>>>s.lower()
'success'
>>>s.capitalize()
'success'
>>>s.swapcase()
'success'
移除字符串首尾指定字符
>>>s = '\tsuccess\n'
>>>s.strip()
'success'
判断字符串的组成
>>>s = 'success'
>>>s.isalnum()
true
>>>s.isalpha()
true
>>>s.isdigit()
false
练习
去除字符串中的空格
方法一
>>>s = 'succ ess'
>>>s = s.replace(' ', '')
>>>s
'success'
方法二
>>>s = 'succ ess'
>>>s = ''.join(s.split())
>>>s
'success'