这就是我所拥有的。这是一个程序,我必须在其中获取一个随机字符串,例如("]][][sfgfbd[pdsbs]\bdgb"; 并去除所有特殊字符。 函数"条带"为其目的工作。
message=(str.lower(input("Enter a Coded message: ")))
offset=int(input("Enter Offset: "))
alphabet="abcdefghijklmnopqrstuvwxyz"
def strip(text):
print("Your Lower case string is: ",message)
print("With the specials stripped: ")
for index in text:
if index in alphabet:
print(index, end="")
print()
return strip
我需要"解码"函数中 strip 的输出,但我似乎无论如何都无法弄清楚存储"索引"的迭代
def decode(character):
encrypted= ""
for character in message:
global offset
if character == " ":
encrypted+= " "
elif ord(character) + offset > ord("z"):
encrypted+=chr(ord(character) +offset - 26)
else:
encrypted+= chr(ord(character)+(offset))
print("the decoded string is: ",encrypted,end=" ")
print()
因此,"解码"仅从原始"消息"输入中获取输出。然而,"佩林"成功地获得了解码的价值。
def palin(code):
print(code[::-1])
print(code[:])
if code[::-1]==code[:]:
print("This is a Palindrome!")
else:
print("This is not a Palindrome.")
return palin
print()
palin(decode(strip(message)))
不要混淆print
和return
。
您需要仔细查看方法的输出(它们返回的内容,而不是它们打印到控制台的内容(:
strip()
和palin()
方法返回对自身的引用,而不是与其输入相关的任何有用内容。decode()
方法不返回任何内容。
若要解决此问题,可以在方法中使用基于输入变量生成的变量,使用所需的逻辑。例如:
def strip(text):
print("Your Lower case string is: ",text)
print("With the specials stripped: ")
stripped_text = "" # <-- create and initialise a return variable
for index in text:
if index in alphabet:
stripped_text += index # <-- update your return variable
print(index, end="")
print()
return stripped_text # <-- return the updated variable
然后你需要对decode()
做类似的事情,尽管这里你已经有一个输出变量(encrypted
(,所以你只需要在方法的末尾return
它。
palin()
方法不需要返回任何内容:它只是打印出结果。
一旦你开始工作,你应该考虑如何使用Python语言的其他功能来更轻松地实现你的目标。
例如,您可以使用replace()
来简化strip()
方法:
def strip(text):
return text.replace('[^a-z ]','') # <-- that's all you need :)