gpt4 book ai didi

python - 在python中打印文本和变量时如何去掉空格

转载 作者:行者123 更新时间:2023-11-28 22:52:57 26 4
gpt4 key购买 nike

我想让用户输入他的姓名/年龄,然后输出十年后的姓名和年龄。我是这样设置的:

    print("Let's find out how old you will be in 10 Years.\n")
name = input("name: ")

print("\nNow enter your age,",name,"\n")
age = int(input("age: "))

ageinten = age + 10

print("\n",name,"you will be",ageinten,"in ten years.")

input("Press Enter to close")

输出是这样的:

    Let's find out how old you will be in 10 Years.

name: Example

Now enter your age, Example

age: 20

Example you will be 30 in ten years.
Press Enter to close

但我希望示例前没有空格:

    Example you will be 30 in ten years.
Press Enter to close

谁能帮忙解决这个问题?

最佳答案

更好用string formatting :

print('\n{} you will be {} in ten years.'.format(name, ageinten))

或使用 sep='',但您必须在字符串的尾随和前导空格中添加空格。

print("\n", name, " you will be ", ageinten, " in ten years.", sep='')

sep 的默认值是一个空格,这就是为什么你要得到一个空格。

演示:

>>> name = 'Example'
>>> ageinten = '20'
>>> print("\n",name," you will be ",ageinten," in ten years.", sep='')

Example you will be 20 in ten years.
>>> print('\n{} you will be {} in ten years.'.format(name, ageinten))

Example you will be 20 in ten years.

关于python - 在python中打印文本和变量时如何去掉空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19856976/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com