2015-06-21 47 views
-2

如何使用python引用字符串中的整数?我对编码完全陌生,我试图做这个bug收集练习,用户将输入一周中每天收集的错误数量,并显示一周结束时收集的错误总数。参考字符串内的整数? Python

这是我到目前为止的代码。

totalBugs = 0.0 
day = 1 

for day in range(7): 
    bugsToday = input('How many bugs did you get on day', day,'?') 
    totalBugs = totalBugs + bugsToday 

print 'You\'ve collected ', totalBugs, ' bugs.' 

,所以我试图让内循环bugsToday提示询问 用户“有多少错误你第1天收?” “您在第2天收集了多少个错误?” 等等。

我该怎么做?

+0

你想“从用户输入读取”。检查:http://stackoverflow.com/questions/3345202/python-getting-user-input – doublesharp

+0

可能的重复[如何将字符串转换为整数在Python?](http://stackoverflow.com/questions/642154/如何将字符串转换为整数在Python中) – Paul

+0

's =“34”''n = int(s)''print n + 1'' 35' – Paul

回答

1

我会做如下的方式。 http://www.learnpython.org/en/String_Formatting

文章,我写的raw_input左右与输入为安全起见,如果你在一个有兴趣:

total_bugs = 0 #assuming you can't get half bugs, so we don't need a float 

for day in xrange(1, 8): #you don't need to declare day outside of the loop, it's declarable in the for loop itself, though can't be refernced outside the loop. 
    bugs_today = int(raw_input("How many bugs did you collect on day %d" % day)) #two things here, stick to raw_input for security reasons, and also read up on string formatting, which is what I think answers your question. that's the whole %d nonsense. 
    total_bugs += bugs_today #this is shorthand notation for total_bugs = total_bugs + bugs_today. 

print total_bugs 

要在字符串格式化读了https://medium.com/@GallegoDor/python-exploitation-1-input-ac10d3f4491f

从Python文档:

CPython实现细节:如果s和t都是字符串,一些Python实现(如CPython)通常可以执行一个就地优化形式为s = s + t或s + = t的点燃。如果适用,这种优化使得二次运行时间不太可能。这种优化是版本和实现相关的。对于性能敏感的代码,最好使用str.join()方法,以确保不同版本和实现之间的一致性线性级联性能。

编程起初看起来不堪一击,只要坚持下去就不会后悔。祝你好运,我的朋友!

+0

谢谢!这正是我正在寻找的!我一定会记得%d。 –

+0

没问题,很乐意帮忙。我可能错过了一些东西,xrange比范围更快,所以我习惯性地使用它。 (1,8)1-7而不是0-6,我虽然更好,但取决于你。我在raw_input上使用了int(),因为raw_input返回一个字符串,我们需要一个int类型。还要注意,%d是整数,%s是字符串,%f是浮点数等,你可能会发现.format方法更容易。 –

1

您可以尝试

... 
for day in range(7): 
    bugsToday = input('How many bugs did you get on day %d ?' % day) 
    totalBugs = totalBugs + bugsToday 
... 
2

我个人很喜欢format()。你可以写代码如下:

totalBugs = 0 
for day in range(1, 8): 
    bugsToday = raw_input('How many bugs did you get on day {} ?'.format(day)) 
    totalBugs += int(bugsToday) 

print 'You\'ve collected {} bugs.'.format(totalBugs) 

range(1, 8)经过day = 1day = 7,如果这是你想要做什么。