格式化字符串遇到 ValueError: incomplete format
今天在使用格式化字符串时遇到如下报错,可是不明白为什么我重新赋值,再输出后就没有出现问题了,不明白哪里出问题了,请大家指教,应该很简单的,但我就没想明白。
In [1]: a = 'pyth'
In [2]: b = 'on'
In [3]: 's%s%' % (a, b)
---------------------------------------
ValueError Traceback (most recent call last)
/home/lijy/<ipython console> in <module>()
ValueError: incomplete format
In [4]: "s% s%" % (a, b)
---------------------------------------
ValueError Traceback (most recent call last)
/home/lijy/<ipython console> in <module>()
ValueError: incomplete format
In [5]: a = "python"
In [6]: b = "learn"
In [7]: "%s %s" % (a,b)
Out[7]: 'python learn'
In [8]: '%s %s' % (a,b)
Out[8]: 'python learn'
In [9]: a = 'python'
In [10]: b = 'learn'
In [11]: '%s %s' % (a,b)
Out[11]: 'python learn'
In [12]: '%s %s' % (a, b)
Out[12]: 'python learn'
In [13]: '%s%s' % (a, b)
Out[13]: 'pythonlearn'
[解决办法]
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> a = 'pyth'
>>> b = 'on'
>>> 's%s%' % (a, b)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
's%s%' % (a, b)
ValueError: incomplete format
>>> '%s%s' % (a, b)
'python'
>>>
因为格式化字符串中 s 需要位于 % 后面