[英]how to store all iterations of a for loop in python
這就是我所擁有的。 這是一個我必須采用隨機字符串的程序,例如)“]] [] [sfgfbd [pdsbs] \\ bdgb”; 並刪除所有特殊字符。 “ Strip”功能可達到其目的。
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
我需要“解碼”功能中帶材的輸出,但無論如何我似乎無法弄清楚存儲“索引”的迭代次數
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()
因此,“解碼”僅采用原始“消息”輸入的輸出。 但是,“ Palin”成功獲取了解碼的值。
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 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.