[英]Print won't work in if statement
當我運行該腳本時,它會跳過第8行中的打印功能。 我已經嘗試了很多事情來使它起作用,但是我似乎無法在這里找出問題所在。 我對Python非常陌生,所以請問這是一個非常簡單的問題。
編輯:哇,忘記了實際的代碼! facepalm在這里是:
import webbrowser
import sys
b = webbrowser.get('windows-default')
print('Type start')
line1 = sys.stdin.readline()
start = 'start'
if line1 == start:
print('What website do you want to open?')
line2 = sys.stdin.readline()
b.open(line2)
當您在stdin中鍵入'start'
然后按Enter時, 包括換行符的整個字符串最終存儲在line1
。 所以實際上, line1 == 'start\\n'
。 在進行比較之前,需要從字符串末尾刪除\\n
。 一種簡單的方法是使用str.rstrip
:
if line1.rstrip() == start:
print('What website do you want to open?')
編輯:
正如Ashwini Chaudhary在評論中指出的那樣,您實際上應該只使用raw_input
(如果使用Python 3.x,則使用input
)而不是sys.stdin.readline
。 這將使您的代碼更短,並且不需要完全刪除尾隨的換行符:
line1 = raw_input('Type start')
start = 'start'
if line1 == start:
line2 = raw_input('What website do you want to open?')
b.open(line2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.