第7章,用Python自动化无聊的东西,实践项目:strip()的regex版本

2024-04-27 21:11:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读一本书“用Python自动化那些无聊的东西”。在第7章中,在项目实践:strip()的regex版本中,这里是我的代码(我使用Python 3.x):

def stripRegex(x,string):
import re
if x == '':
    spaceLeft = re.compile(r'^\s+')
    stringLeft = spaceLeft.sub('',string)
    spaceRight = re.compile(r'\s+$')
    stringRight = spaceRight.sub('',string)
    stringBoth = spaceRight.sub('',stringLeft)
    print(stringLeft)
    print(stringRight)

else:
    charLeft = re.compile(r'^(%s)+'%x)
    stringLeft = charLeft.sub('',string)
    charRight = re.compile(r'(%s)+$'%x)
    stringBoth = charRight.sub('',stringLeft)
print(stringBoth)

x1 = ''
x2 = 'Spam'
x3 = 'pSam'
string1 = '      Hello world!!!   '
string2 = 'SpamSpamBaconSpamEggsSpamSpam'
stripRegex(x1,string1)
stripRegex(x2,string2)
stripRegex(x3,string2)

这里是输出:

Hello world!!!   
      Hello world!!!
Hello world!!!
BaconSpamEggs
SpamSpamBaconSpamEggsSpamSpam

所以,我的regex版本的strip()几乎和原始版本一样。在原始版本中,无论您传入“Spam”、“pSam”、“mapS”、“Smpa”,输出总是“baconspamegs”。。。那么如何在Regex版本中修复这个问题???


Tags: 版本rehelloworldstringregexstripprint