字符串
序列操作:
>>> S = 'spam' >>> S[1] #从正面开始,偏移量开始为0 'p' >>> S[-1] #从后面开始,偏移量开始为-1 'm' >>> S[1:] #切片,偏移量从第二到结尾 'pam' >>> S[:-1] # 'spa' >>> S * 2 'spamspam' >>> S + 'SPAM' 'spamSPAM' >>> len(S) 4
特定类型操作:
>>> S
'spam'
>>> S.find('a') #返回索引号
2
>>> S.find('A') #没有则返回‘-1’
-1
>>> S.replace('S','Z') #替换
'spam'
>>> line = 'aaa,bbb,ccc'
>>> line.split(',') #分隔
['aaa', 'bbb', 'ccc']
>>> line.upper() #大写
'AAA,BBB,CCC'
>>> line.isalpha() #字母判断
False
>>> S.isalpha()
True
>>> line = 'aaa,bbb,ccc,dd\n'
>>> line
'aaa,bbb,ccc,dd\n'
>>> print(line)
aaa,bbb,ccc,dd
>>> line.rstrip() #移除右空格
'aaa,bbb,ccc,dd'
>>> print(line.rstrip())
aaa,bbb,ccc,dd
#格式化方法
>>> '%s,eggs,%s' % ('spam','bar')
'spam,eggs,bar'
>>> '{0},eggs,{1}'.format('spam','bar')
'spam,eggs,bar'
>>> '{},eggs,{}'.format('spam','bar')
'spam,eggs,bar'
模式匹配
>>> match = re.match('Hello[\t]*(.*)world','Hello python world')#匹配hello开头,后面跟着零个或多个制表符或者空格,接着是任意字符串并将其保存到组中,最后以world结尾
>>> match.group(1)
' python '
>>> match = re.match('[/:](.*)[/:](.*)[/:](.*)','/usr/home/lumberjack')
>>> match.groups()
('usr', 'home', 'lumberjack')
>>> match = re.match('[/](.*)[/](.*)[/](.*)','/usr/home/lumberjack')
>>> match.groups()
('usr', 'home', 'lumberjack')
>>> re.split('[/:]','/usr/home/lumberjack')
['', 'usr', 'home', 'lumberjack']

浙公网安备 33010602011771号