0
這是我第一次嘗試用Python寫東西。我不明白爲什麼文本會進入下一行。我希望它是:移動到下一行python的文本3.4
你想刪除「事件」嗎?
Y或N
但它打印爲:
你想刪除 「事件
」? Y或N
由於
# picks a random string from ideas34.txt
event = random.choice(open('ideas34.txt', 'r').readlines())
choice = int(input('\n' "What would you like to do?" '\n' "1 Random event" '\n' "2 Add a new event" '\n'
"3 Show all events" '\n' "4 Quit" '\n'))
# prints a random event from ideas34.txt
if choice == 1:
print(event)
d = input("Would you like to delete " "\"" + event + "\"? \n Y or N" '\n')
# deletes the event picked
if d == 'Y' or d == 'y':
f = open('ideas34.txt', 'r')
a = [event]
lst = []
for line in f:
for word in a:
if word in line:
line = line.replace(word, '') # deletes event picked from ideas34.txt
lst.append(line)
f.close()
f = open('ideas34.txt', 'w')
for line in lst:
f.write(line)
f.close()
可能因爲你有'\ n'嗎? Y或N –
提示:'.readlines()'在它讀取的行上保留換行符。有幾種方法可以解決這個問題,但是可以看看'str'類型的'.strip'和'.rstrip'方法。 –
@PM 2Ring謝謝,就是這樣。 'event.rstrip()'完成了這項工作。 – catroaring