#!python
# 在 Python 里面,变量从来不会显式的指定类型。
# Python 会在内部算出一个变量的类型并进行跟踪
# 正则表达式部分
# 函数参数传递时只要你有一个命名参数,它右边的所有参数也都需要是命名参数
# import 的搜索路径 添加新路径 sys.path.insert(0, '...')
# Python 使用 try...except 块来处理异常,使用 raise 语句来抛出异常
# 模块是对象,并且所有模块都有一个内置的属性 __name__。
# 一个模块的 __name__ 属性取决于你怎么来使用这个模块。
# 如果你 import 这个模块,那么 __name__ 就是这个模块的文件名,
# 不包含目录的路径或者文件的扩展名
import re
p = re.compile(r'[a-z]+') #前面要加上一个r
#m = p.match('1sss25') #match() 决定 RE 是否在字符串刚开始的位置匹配
m = p.search('112sssss55') # 中间
if m:
print ('Match found: ',m.group())
else:
print ('No match')
#group() 返回被 RE 匹配的字符串 group(组号 组名)
#start() 返回匹配开始的位置
#end() 返回匹配结束的位置
#span() 返回一个元组包含匹配 (开始,结束) 的位置
#findall() 找到 RE 匹配的所有子串,并把它们作为一个列表返回
p2 = re.compile('\d+')
print (p2.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping'))
#finditer() 找到 RE 匹配的所有子串,并把它们作为一个迭代器返回
iterator = p2.finditer('12 drummers drumming, 11 ... 10 ...')
for match in iterator:
print (match.span())
#修改字符串
#方法/属性 作用
#split() 将字符串在 RE 匹配的地方分片并生成一个列表,
#sub() 找到 RE 匹配的所有子串,并将其用一个不同的字符串替换
#subn() 与 sub() 相同,但返回新的字符串和替换次数
p3 = re.compile('x')
print (p3.sub('-', 'abxd'))
#用函数吧10进制替换为16进制
def hexrepl(match):
value = int (match.group())
return hex(value)
#该函数将会被模式中每一个不重复的匹配所调用。
#在每次调用时,函数会被传入一个 `MatchObject` 的对象作为参数
p4 = re.compile(r'\d+')
s = p4.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
print(s)
#正则表达式中加注释 re.VERBOSE
pat = re.compile(r"""
\s* # Skip leading whitespace
(?P<header>[^:]+) # Header name
\s* : # Whitespace, and a colon
(?P<value>.*?) # The header's value -- *? used to
# lose the following trailing whitespace
\s*$ # Trailing whitespace to end-of-line
""", re.VERBOSE)
#.标准输入,标准输出和标准错误
import sys
s = input('Please enter your name:')
print ("You typed ",s)
f = open("output","w")
print ("You typed ",s,file=f)
f.close()
#for
a = ['A','B','CCCCCCCCCCCCCCCCCC','D'] #链表
for x in a:
print(x)
for x in a[:]: #要操作时选择迭代