![](/img/trans.png)
[英]Chapter 7, Automate the boring stuff with Python, practice project: regex version of strip()
[英]Regex Version of Strip() - Automate the Boring Stuff with Python
我一直在努力學習如何使用 Al Sweigert 的書進行編碼。 現在我被困在讓程序從單個輸入中獲取文本和/或參數。 我知道使用兩個單獨的輸入更簡單,但我想只使用一個。
我也不知道正則表達式中 r' 和 rf' 之間有什么區別。
#python 3
#A program that does exactly the same thing as the split function
import re
def striperoo(text, argument):
if argument != '':
argRegex = re.compile(rf'{argument}')
while True:
argCheck = argRegex.search(text)
if argCheck != None:
startOfArg = argCheck.span()[0]
endOfArg = argCheck.span()[1]
text = text[:startOfArg] + text[endOfArg:]
else:
print(text)
break
else:
spcRegexBegin = re.compile(r'^\s+')
spcRegexEnd = re.compile(r'\s+$')
while True:
spcAtBeginning = spcRegexBegin.search(text)
spcAtEnd = spcRegexEnd.search(text)
if spcAtBeginning != None:
blankSpacesSpan = spcAtBeginning.span()[1]
text = text[blankSpacesSpan:]
elif spcAtEnd != None:
spacesAtEnd = spcAtEnd.span()[0]
text = text[:spacesAtEnd]
else:
print(text)
break
texto, argumento = input('Please type text and argument using the format text, argument: ').split(', ')
striperoo(texto, argumento)
有人可以幫我一把嗎? 正如預期的那樣,當我只輸入一個變量時,出現以下錯誤:
Traceback (most recent call last):
File "C:\strip.py", line 33, in <module>
texto, argumento = input('Please type text and argument using the format text, argument: ').split(', ')
ValueError: not enough values to unpack (expected 2, got 1)
它應該將像' Hola mundo cruel '
'holamundocruel'
類' Hola mundo cruel '
字符串轉換為'Hola mundo cruel'
'AholaAmundoAcruel, A'
'Hola mundo cruel'
和'AholaAmundoAcruel, A'
到'holamundocruel'
。
謝謝,
海梅
如果用戶輸入中沒有', '
.split
將生成包含 1 個元素的列表,您可以相應地檢查它
userinput = input('Please type text and argument using the format text, argument: ').rsplit(', ', maxsplit=1)
if len(userinput) == 1:
texto, argumento = userinput[0], ''
else:
texto, argumento = userinput
請注意,我使用rsplit
並將maxsplit
設置為1
,這意味着它會給出不大於2
的len
list
,而沒有 maxsplit 的split
可能會給出更長的列表。 這意味着如果用戶輸入有多個', '
,它將僅在最右邊的一個處拆分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.