如何将var视为int和string。

时间:2017-07-07 16:11:08

标签: python python-2.x

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 + "."

标准掷骰子游戏,但我努力打印个人骰子以及总数的价值。作为个人的字符串处理,但总和导致连接而不是实际的总和。

由于

6 个答案:

答案 0 :(得分:2)

将变量保留为数字,让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进行一些格式化,以便更好地控制上面的默认参数间距:

print "You have rolled a {} and a {}, for a \
total score of {}.".format(first, second, total)

答案 1 :(得分:1)

有两种方法可以解决您的问题(还有更多!)。首先,在将它们一起添加时,需要确保将整数保持为类型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为您整理和格式化整数值。如果您有4位或更多位数的大数字,这样做的一个优点是您可以使用字符串格式代码(如"my big number: {0:d,}".format(1000000))来使您的字符串输出像"my big number: 1,000,000",这样更易​​读。< / p>

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)

答案 2 :(得分:0)

您可以使用强制转换来更改var的结构。您可以将它们用作字符串并完全使用此行:

 total = int(first) + int(second)

或者将它们用作int并使用str(first)和str(second)将它们转换为print中的字符串

最佳

答案 3 :(得分:0)

print "You have rolled a " + str(first) 这会将int转换为字符串,从而将其连接起来。

另外,你可以这样做 total = int(first) + int(second)解决第一个问题。

答案 4 :(得分:0)

您有两种解决方案:

  1. 在添加数字前将数字转换回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 + ".")
    
  2. 在打印前将数字转换为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) + ".")
    
  3. 任何一种解决方案都可以完美地运行。

答案 5 :(得分:-1)

这也可行。不要将firstsecond转换为str,直到您对它们执行求和为止。然后记得在str声明中将它们投射为print

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 + ".")