我是編程和閱讀「使用Python自動化枯燥的東西」這本書的初學者,在第7章中有一個項目實踐:strip()的正則表達式版本。下面,將strip_chars
不插補,也就是說它是作爲字符串的一部分,處理不工作(我使用Python 3.6.1)。誰能幫助?Python:使用正則表達式的條形函數定義
import re
string = input("Enter a string to strip: ")
strip_chars = input("Enter the characters you want to be stripped: ")
def strip_fn(string, strip_chars):
if strip_chars == '':
blank_start_end_regex = re.compile(r'^(\s)+|(\s)+$')
stripped_string = blank_start_end_regex.sub('', string)
print(stripped_string)
else:
strip_chars_start_end_regex = re.compile(r'^(strip_chars)*|(strip_chars)*$')
stripped_string = strip_chars_start_end_regex.sub('', string)
print(stripped_string)
不工作如何,併爲什麼輸入? –
'r'^(strip_chars)* |(strip_chars)* $'' - >'r'^ [{0}] + | [{0}] + $'.format(「」。join([re.escape (x)for strip_chars]))'。另外,在'r'^(\ s)+ |(\ s)+ $''中刪除不必要的'('和')''。 –