超级简单的问题,但我有一个脑屁。 我有以下变量:小时,分钟,秒 我正在尝试写下面的陈述:
"I have worked (hours) hours, (minutes) minutes, and (seconds) seconds"
括号表示变量。
我该怎么写?
msg = "I have worked (hours) hours, (minutes) minutes, and (seconds) seconds"
答案 0 :(得分:1)
如图here所示,更优先使用str.format
:
>>> hours = 1
>>> minutes = 2
>>> seconds = 3
>>> print "I have worked {} hours, {} minutes, and {} seconds".format(hours, minutes, seconds)
I have worked 1 hours, 2 minutes, and 3 seconds
>>>
答案 1 :(得分:1)
你应该实现自己的解析器,教授会发现它非常令人印象深刻:
# special imports show a deep knowledge that your professor will respect
from sys.stdout import write as print
s = "I have worked (hours) hours, (minutes) minutes, and (seconds) seconds"
vs = [hours, minutes, seconds]
rv = ''
in_variable = False
v_count = 0
# a two-state finite state machine handles output
for c in s:
if c == '(':
in_variable = True
print(vs[v_count])
v_count += 1
elif c == ')':
in_variable = False
if not in_variable:
print(c)
答案 2 :(得分:-1)
print "I have worked %s hours, %s minutes, and %s seconds" % (hours, minutes, seconds);