python±Ê¼ÇÖ®ÕýÔò±í´ïʽ
ÕýÔò±í´ïʽ
¾ßÌåµÄ²Î¿¼ÊֲᣬÕâÀï¼ÇÏÂһЩСÎÊÌ⣺
1¡¢re¶ÔÏóµÄ·½·¨
match Match a regular expression pattern to the beginning of a string.
search re.search(pattern, string, flags) flags:re.I re.M re.X re.S re.L re.U
sub Substitute occurrences of a pattern found in a string.
subn Same as sub, but also return the number of substitutions made.
split Split a string by the occurrences of a pattern.
findall Find all occurrences of a pattern in a string.
finditer Return an iterator yielding a match object for each match.
iter = re.finditer("23", "123423523")
for i in iter:
print i.span()
compile ½«Ò»¸öpattern±àÒë³ÉÒ»¸öRegexObject.
re¶ÔÏóµÄʹÓ÷½·¨£¬reobject = re.complie(pattern)£¬´Óreobject»ñµÃpatternµÄ·½·¨£¬Ê¹ÓÃreobject.patternÊôÐÔ
Èç¹ûÒ»¸öreobjectÒª¶à´ÎʹÓã¬×îºÃʹÓÃcompile·½·¨Ìá¸ßÐÔÄÜ£¬·ñÔò¿ÉÒÔÖ±½Ó°´ÕâÖÖ·½Ê½Ê¹Óã¬re.search(pattern, string)
purge Clear the regular expression cache.
escape Backslash all non-alphanumerics in a string.
2¡¢ÒªÊ¹group(s)·½·¨£¬Ó¦¸ÃÔÚpatternÖжÔÏëÒªÔÚtuplesÖеIJ¿·Ö¼ÓÉÏÀ¨ºÅ£¬ÀýÈç“123-45”£¬ÏëÆ¥ÅäÕâ¸östring£¬µ«ÊÇÖ»Ïë»ñµÃǰÈý¸öÊý×Ö£¬Ôò¿ÉÒÔʹÓÃÕâÑùµÄpattern,"(\d{3})-\d{2}"
,×¢ÒâÇ°ÃæÊ¹ÓÃÁËÀ¨ºÅ£¬ÔÙµ÷ÓÃgroups·½·¨»áµÃµ½tuples,("123",)
¡£group(s)ÊÇSRE_Match object µÄ·½·¨£¬Í¨³£Ê¹Ó÷½·¨Îªreobject.search(string).group(s)
3¡¢ÒªÆ¥ÅäÈÎÒâµ¥¸ö×Ö·ûʹÓÃ"."£¬ÈÎÒâ¸ö×Ö·ûʹÓÃ".*"(°üÀ¨0¸ö)£¬»òÕß".+"(ÖÁÉÙÒ»¸ö)¡£
4¡¢À¨ºÅµÄ¶àÖÖÓ÷¨
(?:)²»·ÅÈëgroupsÖÐ
(?iLmsux) Ϊpattern¼ÓÈëI,L,M,S,U,X±êÖ¾
(?P<name>) ΪgroupµÄÒ»Ïî¼ÓÈë±ðÃû
(?P=name) Æ¥ÅäÔÚ֮ǰÓÃname±íʾµÄ²¿·Ö±í´ïʽËùÆ¥Åäµ½µÄÄÚÈÝ
(?#comment) ×¢ÊÍ
test1(?=test2) Èç¹ûtest1ºóÃæ¸ú×Åte
Ïà¹ØÎĵµ£º
Ô´´úÂëÏÂÔØ£ºÏÂÔØµØÖ·ÔÚÕâÀï
# 029
aFile = file(r'C:\in.txt', 'r')
while True:
line = aFile.readline()
if len(line) == 0:
break
# end of if
print line,
# end of while
aFile.close()
output£º
>>>
This is the first line.
This is the second line.
This is ......
Ô´´úÂëÏÂÔØ£ºÏÂÔØµØÖ·ÔÚÕâÀï
e.g.1
# 030
aFile = file(r'C:\temp.txt', 'a')
aFile.write('ÓÖÌí¼ÓÁËÒ»ÐС£')
aFile.close()
output:
e.g.2
# 030
aFile = file(r'C:\temp.txt', 'a')
aFile.write('ÓÖÌí¼ÓÁËÒ»ÐС£')
aFile.close()
output:
e.g.3
ʵÏÖ¸ù¾ÝÔʼÎļþÓÐûÓÐ×îºóÒ»ÐпÕÐеÄÇé¿öÀ´½øÐÐ&ldqu ......
Ô´´úÂëÏÂÔØ£ºÏÂÔØµØÖ·ÔÚÕâÀï
# 034
class Person:
def __init__(self, name):
self.name = name # ÕâÒ»¾äÖеÚÒ»¸önameÊÇÀàÖаüº¬µÄÓò£¬µÚ¶þ¸önameÊÇ´«½øÀ´µÄ²ÎÊý
# end of def
def sayHello(self):
print 'Hello!'
# end of def
# end of class
p = Person('Ning')
print p.nam ......
Ô´´úÂëÏÂÔØ£ºÏÂÔØµØÖ·ÔÚÕâÀï
# 035
class Person:
population = 0 #Õâ¸ö±äÁ¿ÊÇÊôÓÚÕû¸öÀàµÄ
def __init__(self, name):
self.name = name
print '³õʼ»¯ %s' % self.name
Person.population += 1
# end of def
def __del__(self):
print '%s says bye.' % self. ......
½ñÌì¿´ÁËÐòÁÐÀàÐÍÏà¹ØµÄ±È½Ï²Ù×÷.
ÔÚpythonºËÐıà³Ì(2nd)Ò»ÊéÖÐ6.13.1Õ½ÚÖÐ, ¸ø³öÁËÁбí±È½ÏµÄÒ»¸ö×¼Ôò..
¸öÈ˸оõ»¹ÊDz»ºÜÍêÉÆ:
Èç¹ûɨÃèµ½Á½¸öÁбíÖе±Ç°±È½ÏÔªËØÊDz»¿É±È½ÏµÄ, ÄÇô·µ»ØÊ²Ã´??
ÎÒÓõÄÊÇpython2.6....
¶ÔÕâ¸öÎÊÌâ×öÁËһЩ²âÊÔ, ×Ô¼ºÄ¿Ç°¸Â¾øµ±±È½ÏÓöµ½ÉÏÊöÇé¿öʱ, ÊÇʹÓÃÁ½¸öÁбíµÄÄÚ´æµØÖ·ÖµÀ´±È½ ......