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

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

我想这样做,用户输入他的名字/年龄,并在十年内输出名字和年龄。我是这样安排的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    print("Let's find out how old you will be in 10 Years.
"
)
    name = input("name:")

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

    ageinten = age + 10

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

    input("Press Enter to close")

输出如下:

1
2
3
4
5
6
7
8
9
10
    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

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

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

有人能帮忙解决这个问题吗?


更好地使用字符串格式:

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

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

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

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

演示:

1
2
3
4
5
6
7
8
9
10
>>> name = 'Example'
>>> ageinten =  '20'
>>> print("
"
,name," you will be",ageinten," in ten years.", sep='')

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

Example you will be 20 in ten years.


尝试只使用print()来给出新行。这似乎最适合您当前的风格:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
print("Let's find out how old you will be in 10 Years.
"
)
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")