您好我是CS学生,目前非常新手 我刚才有一个问题,我认为来自这个网站的许多python专家都能回答我的原始问题。
例如
def validNum(initialNum, endingNum):
askNum = input("Please enter a number from initialNum to endingNum")
在main中:
validNum(1, 31)
但在这种情况下,提示中的initialNum和endingNum是字符串,因此结果将是
"Please enter a number from initialNum to endingNum"
但我想要
"Please enter a number from 1 to 31"
有没有pythonic的方法来做到这一点?
答案 0 :(得分:1)
您可以使用str.format()
来完成您的任务,例如:
def validNum(initialNum, endingNum):
askNum = input("Please enter a number from {0} to {1}: ".format(initialNum, endingNum))
validNum(1,31)
否则,您可以使用%
和format specification mini-language获得相同的结果:
# if your input is a decimal:
askNum = input("Please enter a number from %d to %d: " % (initialNum, endingNum))
# if your input is a float:
askNum = input("Please enter a number from %f to %f: " % (initialNum, endingNum))
# or simply
askNum = input("Please enter a number from %r to %r: " % (initialNum, endingNum))
# or maybe
askNum = input("Please enter a number from %(initial)s to %(ending)s: " % {'initial': initialNum, 'ending': endingNum})
答案 1 :(得分:1)
在Python 3.6中,您只需要新的f-string:
def validNum(initialNum, endingNum):
askNum = input(f"Please enter a number from {initialNum} to {endingNum}")
注意要插入的变量的前导f
和花括号。