Python程序设计之字符替换(正则表达式)

案例1.
将字符串中,字母i单独出现的地方将i变为I

import re
#1将字符串中,字母i单独出现的地方将i变为I
s='i am is wang i love I love you i!'
patter=re.compile(r'\bi\bi{0}')
print(patter)
print(re.sub(patter,'I',s)) #方法一
print(re.sub(r'\bi\bi{0}','I',s))#方法二使用原始字符串,减少输入字符的数量
print(re.sub('\\bi\\bi{0}','I',s))    #方法三使用"\"开头的元字符
print(re.sub('\\bi\\b','I',s))
#print(re.sub(r'\bl.*?\b','A',s))   #匹配所有以l开头的单词并替换为A
#print(re.sub('\\bl.+?\\b','A',s))
print('',end='\n')

案例2.
把字符串中字母I位于单词中出现的地方组转换为小写

s1='I love you and hIs bautIfule nIce!'
patter1=re.compile(r'\BI+')
print(re.sub('\\BI+','i',s1))
print(re.sub(patter1,'i',s1))
print('',end='\n')

案例3
驻留机制的代码分析

s3='1234'
sS='1234'
print('短字符串id:')
print(id(s3))
print(id(sS))
print(id(s3)==id(sS))
s3=s3 * 100
sS=sS * 100
print('改变后长字符串id')
print(id(s3))
print(id(sS))
print(id(s3)==id(sS))   #短字符串具有驻留性,但对变量进行分别变长后,地址发生变化
print('',end='\n')

案例4
用户输入一段英文,输出所有长度为3的单词

s4=str(input("Please input an nice his  you english story:"))
patter4=re.compile(r'\b[\w+]{3}\b')
#print(re.search(patter4,s4))
print(' '.join(re.findall(patter4,s4)),end='\n')    #方法一
#print(re.sub('^\b[\w+]{3}\b','',s4))    #方法二

Python正则表达式详解:
https://blog.csdn.net/qxyloveyy/article/details/104465643
Python字符串详解:
https://blog.csdn.net/qxyloveyy/article/details/104449051
Python字符串使用案例:
https://blog.csdn.net/qxyloveyy/article/details/104449051
代码链接:
https://download.csdn.net/download/qxyloveyy/12188558

发布了78 篇原创文章 · 获赞 83 · 访问量 5420

猜你喜欢

转载自blog.csdn.net/qxyloveyy/article/details/104482502