python 中的格式化字符串出错

Formatting string in python going wrong

以下是我的代码片段。

bar = "Hello World"
print("%5s" % bar)

我正在尝试从 bar 打印 Hello。但是 %5s 没有正常工作。

我做错了什么?

这样做更简单:

bar = "Hello World"

print (bar[:5])

使用“%5s”只会 return 整个字符串,因为该字符串的长度 >5 个字符,例如,如果您使用“%20”,您将得到白色 space 后跟整个字符串字符串,像这样。

bar = "Hello World"
print("%20s" % bar)
>>>         Hello World

在以下代码中:

bar = "Hello World"
print("%5s" % bar)

bar 的总宽度应超过 5 个字符,否则 padding spaces 将被添加为前缀。

此处填充为 5 但字符串长度为 11。所以什么都不会发生。

在以下代码中:

bar = "Hello World"
print("%15s" % bar)

填充 15 超过字符串长度 11。因此 4 space 将在开头添加。

输出将是:----Hello World

-表示一个space.

%5s 如果字符串短于 5 个字符,则用空格填充 例如

>>> print("%5s" % "Hi")
   Hi

要截断字符串,您可以使用 %.5s

>>> bar = "Hello World"
>>> print("%.5s" % bar)
Hello

或者可以将字符串切片如下

>>> bar = "Hello World"
>>> print("%s" % bar[:5])
Hello