python变量命名的正则表达式_Python_正则表达式练习

#!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&ltheader&gt[^:]+) # Header name

\s* : # Whitespace, and a colon

(?P&ltvalue&gt.*?) # 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[:]: #要操作时选择迭代

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值