引用字符串内的整数?Python

2024-09-29 22:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用python引用字符串中的整数?我对编码完全陌生,我正在尝试做这个bug收集练习,用户将输入一周内每天收集的bug数量,并在周末显示收集到的bug总数。在

这是我目前掌握的密码。在

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提示符来询问用户 “第一天你收集了多少虫子?” “第二天你收集了多少虫子?” 等等。在

我该怎么做?在


Tags: 字符串用户密码编码for数量整数bug
3条回答

我个人很喜欢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 = 1到{},如果你想这样做的话。在

你可以试试

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

我的方法如下。在

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

要阅读字符串格式:http://www.learnpython.org/en/String_Formatting

我写了一篇关于原始输入和出于安全目的的输入的文章,如果你感兴趣的话:https://medium.com/@GallegoDor/python-exploitation-1-input-ac10d3f4491f

来自Python文档:

CPython implementation detail: If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s = s + t or s += t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

编程一开始似乎让人不知所措,坚持下去你不会后悔的。祝你好运,我的朋友!在

相关问题 更多 >

    热门问题