[英]How to treat a var as both int and string.
def die():
first = str(randint(1, 6))
second = str(randint(1, 6))
total = first + second
print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."
标准的掷骰子游戏,但是我很难打印单个骰子的值以及总数。 将其视为单个字符串,然后求和会导致串联,而不是实际求和。
谢谢
将变量保留为数字,并让print
执行格式化:
def die():
first = randint(1, 6)
second = randint(1, 6)
total = first + second
print "You have rolled a", first, "and a", second, ", for a total score of", total, "."
或者,您可以使用str.format
进行一些格式化,以str.format
地控制上述默认参数间的间距:
print "You have rolled a {} and a {}, for a \
total score of {}.".format(first, second, total)
有两种方法可以解决您的问题(还有更多方法!)。 首先,您需要确保将整数加在一起时将整数保留为int
类型,然后在打印出来时将其转换为字符串。
您可以使用str()
强制转换方法和+
级联,如下所示进行操作。
def die1():
"""Roll and print two dice using concat."""
first = randint(1, 6) # keep these as integers
second = randint(1, 6)
total = first + second # so addition works
# but now cast to str when printing
print "You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + "."
但是更方便的方法是使用str.format()
方法在字符串中放置占位符,然后让python为您str.format()
和格式化整数值。 如果您有4个或更多数字的大数字,那么这样做的好处是,您可以使用字符串格式代码,例如"my big number: {0:d,}".format(1000000)
以使字符串输出类似于"my big number: 1,000,000"
,可读性更高。
def die2():
"""Roll and print two dice using str.format()."""
first = randint(1, 6)
second = randint(1, 6)
total = first + second
# or use the str.format() method, which does this for you
print "You have rolled a {0} and a {1}, for a total score of {3}.".format(first, second, total)
您可以使用强制转换来更改var的结构。 您既可以将它们用作字符串,也可以使用以下代码行:
total = int(first) + int(second)
或将它们用作int并通过使用str(first)和str(second)将它们转换为打印结果中的字符串
最好
print "You have rolled a " + str(first)
这会将int转换为字符串,从而将其连接起来。
此外,您可以执行total = int(first) + int(second)
解决第一个问题。
您有两种解决方案:
在添加数字之前将其转换回int
:
def die(): first = str(randint(1, 6)) second = str(randint(1, 6)) total = str(int(first) + int(second)) print ("You have rolled a " + first + " and a " + second + ", for a total score of " + total + ".")
在打印数字之前将其转换为str
:
def die(): first = randint(1, 6) second = randint(1, 6) total = first + second print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + ".")
两种解决方案都可以正常工作。
这也将起作用。 在对它们执行求和之前,请勿将first
和second
转换为str
。 然后记住在print
语句中将它们转换为str
。
def die():
first = randint(1, 6)
second = randint(1, 6)
total = str(first + second)
print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + total + ".")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.