在Python中,如何删除空间?

2024-10-05 14:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

执行代码后,我得到以下打印输出:

"Het antwoord van de berekening is: 8775 ."

当我想得到“安特伍德范德贝雷肯是:8775。”。所以我想去掉数字和点之间的空格。我该怎么做?你知道吗

Berekening1 = 8.5
Berekening2 = 8.1+4.8
Berekening3 = 8*10
Berekening4 = 3
x = Berekening1 * Berekening2 * Berekening3 + Berekening4
print "Het antwoord van de berekening is:",
print int(x),
print "."

Tags: 代码isde数字van空格print打印输出
3条回答

您可以使用:

print "Het antwoord van de berekening is: {}.".format(x)

不要使用print ..,,它会添加空格,因为你让它用逗号。改用字符串格式:

print "Het antwoord van de berekening is: {}.".format(x)

这里的{}是一个占位符,一个将第一个参数放入str.format()方法的槽。.紧跟其后:

>>> x = 42
>>> print "Het antwoord van de berekening is: {}.".format(x)
Het antwoord van de berekening is: 42.

您也可以使用字符串连接,但这更麻烦:

 print "Het antwoord van de berekening is: " + str(x) + "."

你不想用Python3吗?在python3中,print是一个函数,它接受可选的关键字参数,可以根据您的需要修改其行为

In [1]: help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

这如何适用于你的问题(或者说,老实说,根据Padraic的评论,你对成为你问题的任务的特定方法)?你有两种可能

In [2]: print('The result is ', 8775, '.', sep='')
The result is 8775.

In [3]: print('The result is ', end=''); print(8755, end=''); print('.')
The result is 8775.

In [4]:

如果您还停留在python2中,那么仍然可以利用print作为函数从__future__导入此行为,使用

from __future__ import print_function

在你的程序里。你知道吗

如果你不太了解这些东西,SO is your friend

相关问题 更多 >