我正在閱讀「使用Python自動化枯燥的東西」第7章,在項目實踐中:正則表達式版本的條(),這裏是我的代碼(我使用Python 3.X):第7章使用Python自動化枯燥的東西練習項目:正則表達式版本的條()
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
所以,我帶的正則表達式版本()幾乎與原工作版本。在原始版本中,無論您傳入「垃圾郵件」,「pSam」,「mapS」,「Smpa」,輸出總是「BaconSpamEggs」...所以如何在f這在正則表達式版本?
那麼有沒有關於正則表達式的奧祕。所以你遇到的問題是你已經失去了對代碼流的控制。 – sln
什麼是「原始版本」? –
「原始版本」是本書第6章中介紹的strip()默認方法。例如: spam ='SpamSpamBaconSpamEggsSpamSpam') 其中您輸入:spam.strip('Spam')或spam.strip('Smap')或spam.strip('pSam')...輸出總是:BaconSpamEggs –