How to get rid of spaces when printing text and variables in python

纵然是瞬间 提交于 2019-12-02 01:58:02

问题


I want to make it so the user enters his name/age and it outputs the name and age in ten years. I have set it out like this:

    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")

The output is like this:

    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

But I want it without the space before example:

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

Can anyone help with this problem?


回答1:


Better use string formatting:

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

or use sep='', but then you'd have to add trailing and leading spaces to the strings.:

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

Default value of sep is a space, that's why you're getting a space.

Demo:

>>> 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.



回答2:


Try using just print() to give out newlines. This seems to fit your current style most:

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")


来源:https://stackoverflow.com/questions/19856976/how-to-get-rid-of-spaces-when-printing-text-and-variables-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!