我仍然只学习Python的基础知识,但我的代码是:
name = input("Hi, what is your name? ")
print("Hi,", str(name), ". We need to check your funds for all your drinking,", name, ".")
当我运行它时,我输入'Bojack'(没有引号),但它总是会回来:
Hi, Bojack . We need to check your funds for all your drinking, Bojack .
如何解决此问题?
答案 0 :(得分:2)
你可以打印这样的字符串:
print("My name is {name}.".format(name=name))
答案 1 :(得分:1)
问题不是(正如您认为的那样)name
被分配'Bojak '
(带空格) - 问题是当print()
像那个python3分开时默认情况下带有空格的争论。
你可以通过传递sep
争论来覆盖它:
print("Hi,", str(name), ". We need to check your funds for all your drinking,", name, ".", sep="")
答案 2 :(得分:0)
发生这种情况的原因是您使用逗号(,
)加入字符串。避免这种情况发生的一种方法是使用字符串连接:
name = input("Hi, what is your name? ")
print("Hi, " + name + ". We need to check your funds for all your drinking, " + name + ".")
输出:
Hi, Bojack. We need to check your funds for all your drinking, Bojack.
虽然这个解决方案不是最有效和最干净的,但对于Python初学者来说很容易理解。对于更快的解决方案,字符串格式化更好。
希望这有帮助!