[英]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.