我想检查的是用户输入是否为空字符串。我想要代码执行和输出:"没有输入"但是每当我输入没有输入时,它转到下一个if语句并用空值执行。
import urllib
import re
myString = " "
i = 0
def getStockPrice():
text_file = open("data.txt", "w")
url = "http://finance.yahoo.com/q?s=" + symbolslist
htmlfile = urllib.urlopen(url)
htmltext = htmlfile.read()
regex = '<span id="yfs_l84_' + symbolslist+ '">(.+?)</span>'
pattern = re.compile(regex)
price = re.findall(pattern,htmltext)
if str(price) == myString:
print "No input"
else:
print "the price of", symbolslist," is ", price
text_file.write(str(price))
text_file.close()
dino = raw_input("What stock would you like to Check?: ")
symbolslist = dino
getStockPrice()
while i < 1000:
lilly = raw_input("What other stocks do you want to check?: ")
symbolslist = lilly
getStockPrice()
答案 0 :(得分:0)
“空字符串是len(String)== 0。在你的情况下len(MyString)== 1”_wanderlust2
这给了我一些关于这个问题的见解,我犯这个错误对我来说非常业余。谢谢!
答案 1 :(得分:0)
在Python中,空字符串的计算结果为False
。这意味着您可以使用简单的代码来改进if语句:
user_input = raw_input("Stock to check")
user_input = user_input.strip() # be sure to clear any whitespace!
if user_input:
# continue on with your program
...
如果您使用此Python习惯用法,您的代码将更简洁,更易于阅读。如果您习惯了它,您也将了解使用该功能的其他Python程序。
对于你的代码,我会重构你所拥有的东西:
while True:
user_input = raw_input("Stock to check")
user_input = user_input.strip() # be sure to clear any whitespace!
if user_input:
if user_input.lower() == 'quit':
break
getStockPrice(user_input)
这将依赖于您更改getStockPrice
函数以接受参数!这是一个简单的改变。尝试在括号中添加额外的字词:
def getStockPrice(symbolslist):