Python - 模数格式变量

Python - Modulus format variable

当我将以下内容作为 Python 代码输入 Notepad++ 时:

days = "Mon"

print "Here are the days: %s ". % days   

我在 Windows Powershell 中得到这个输出:

File "ex9exp.py", line 4
print "Here are the days: %s ". % days  

我不知道为什么会这样。

我打算输出

print "Here are the days: %s ". % days 

成为

Here are the days: Mon  

希望得到一些帮助。

问题是您使用的 print 函数的语法错误。

>>> days = "Mon"
>>> 
>>> print "Here are the days: %s ". % days   
  File "<stdin>", line 1
    print "Here are the days: %s ". % days   
                                    ^
SyntaxError: invalid syntax

删除 .。并尝试

>>> print "Here are the days: %s " % days   
Here are the days: Mon 

。在字符串之后是一些语言中使用的运算符,如 PHP 用于附加字符串,但它在 Python 中不起作用,因此代码如下:

days = "Mon"

print "Here are the days: %s ". % days   

产生以下输出:

   File "h.py", line 3
     print "Here are the days: %s ". % days
                                     ^ SyntaxError: invalid syntax

让您知道 compiler/interpreter 并不期待“.”。

删除 . 即可解决问题,如下所示:

days = "Mon"

print "Here are the days: %s " % days 

它将以这种方式工作。

您还可以使用 + 附加字符串

print "Here are the days: " + days

会起作用