使用Python还原文本文件中的字符串
我尝试了下面的代码,因为我试图按相反的顺序进行推送,但没有返回
import TStack as Stack
f=open('months.txt','r')
data=Stack.create()
for line in f:
Stack.push(data,line)
while not Stack.is_empty(data):
removed=Stack.pop(data)
here=Stack.push(data,removed)
list returns None
答案 0 :(得分:0)
您可以使用堆栈使用与反转行相同的过程来编写字符串反转:
import TStack as Stack
def reverse_string(s):
stk = Stack.create()
for c in s:
Stack.push(stk, c)
result = ""
while not Stack.is_empty(stk):
result += Stack.pop(stk)
return result
f=open('months.txt','r')
data=Stack.create()
for line in f:
Stack.push(data,line)
while not Stack.is_empty(data):
print(reverse_string(Stack.pop(data)))
您还可以在将每一行添加到堆栈中时反转它们;
# ...
for line in f:
Stack.push(data, reverse_string(line))
while not Stack.is_empty(data):
print(Stack.pop(data))