Python中的str
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'