【问题标题】:how to get a variable then a string without a space in python如何在python中获取一个变量然后是一个没有空格的字符串
【发布时间】:2017-05-09 13:43:41
【问题描述】:

所以我做了这个并且它有效,但我有点挑剔,所以我希望它 100% 有效。这是代码

import random
input_1 = str(input("Do you want to roll a dice? Enter y for yes anything else for no. "))
if input_1 == "y":
    dicesides = int(input("How many sides do you want your dice to have? "))
    diceroll = random.randint(1, dicesides)
    print("The dice rolled a",diceroll ".")
    input_2 = str(input("Do you want to roll the dice again? Same keys. "))
    while input_2 == "y":
        print(random.randint(1, dicesides))
        input_2 = str(input("Do you want to roll the dice again? Same keys. "))
    else:
        print("Okay, goodbye now.")

else:
    print("Okay, goodbye now.")

当代码运行时,它会告诉我它“滚动”的数字,但它会在数字后放置一个空格。我不想要这种行为。 在我找出如何将第二个+骰子改为它之后。

想通了,谢谢!

【问题讨论】:

  • print("The dice rolled a",diceroll ".") 是无效的语法。我想你想要print("The dice rolled a {}.".format(diceroll))

标签: python-3.x random while-loop


【解决方案1】:

查看print 函数的帮助页面。如果给定一个参数列表,它会打印它们,并以 sep 参数的值分隔,默认情况下是一个空格。所以:

print("This",1,"is",2,"spaced",3,"out.")
print("This",1,"is",2,"not.",sep="")

会有不同的表现。您需要使用 sep="" 并将自己的尾随或前导空格手动添加到字符串中,如下所示:

print("You rolled a ", roll, ".", sep="")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2013-03-17
    • 1970-01-01
    • 2015-04-14
    相关资源
    最近更新 更多