Python Learning Summary

Python methods and module

1.String methods

  • strip()  

Description

The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).

Example:

str='0000str000aaa000'
print str.strip('0')

Result :

 'str000aaa'

2. re module

  • re.search

re.search(patternstringflags=0)

return a corresponding match object, return None if not match pattern, group(0) return full match, group(1) return first match, group(2) return second match

Example:

import re
m = re.search('(1).*','123')
print m.group(0)
print m.group(1)

Result:

'123'
'1'

 

  • re.sub 

re.sub(patternreplstringcount=0flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern. For example:

import re
print re.sub('\d','a','123')

Result:

'aaa'

 

  •  re.findall

 

re.findall(patternstringflags=0)

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. For example:

import re
print re.findall('12','12111222')
print re.findall('(1)(2)','12111222')

Result:

['12', '12']
[('1', '2'), ('1', '2')]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值