如何在python中打印文本和变量时删除空格

时间:2013-11-08 10:39:04

标签: python python-3.x printing space

我想这样做,以便用户输入他的姓名/年龄,并在十年内输出姓名和年龄。我已经这样设置了:

    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

任何人都可以帮忙解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

更好地使用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.

答案 1 :(得分:0)

尝试仅使用print()来提供换行符。这似乎最符合你目前的风格:

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

print()
print("Now enter your age,",name)
print()
age = int(input("age: "))

ageinten = age + 10

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

input("Press Enter to close")